go 带*号是指针型的, 所以要先初始化这个Address

package main
import (
	"fmt"
)

type Address struct {
	Province string
	City string
	CreateTime string
}

type Email struct {
	Account string
	CreateTime string
}

type User struct {
	Username string
	Sex string
	City string  // 自己有的默认使用自己的
	Age int	
	AvatarUrl string
	*Address
	*Email
	// CreateTime string
}

func test(){
	var user User  // 变量名不能和包名相同,否则会 冲突了
	user.Username = "user01"
	user.Age =18
	user.Sex ="男"
	// user.Province ="湖北"
	user.City ="黄冈"
	fmt.Printf("user=%#v addr=%#v\n",user,user.Address)
	fmt.Printf("user=%#v addr=%#v\n",user,user.City)
}

func test1(){
	var user User  // 变量名不能和包名相同,否则会 冲突了
	user.Username = "user01"
	user.Age =18
	user.Sex ="男"
	user.Address = new(Address)  // 带*号是指针型的, 所以要先初始化这个Address
	user.Province ="湖北"
	user.Address.City ="黄冈"
	fmt.Printf("user=%#v\n addr=%#v\n",user,user.Address)
}

func test2(){
	var user User  // 变量名不能和包名相同,否则会 冲突了
	user.Username = "user01"
	user.Age =18
	user.Sex ="男"
	user.Address = new(Address)  // 带*号是指针型的, 所以要先初始化这个Address
	user.Province ="湖北"
	user.Address.City ="黄冈"
	user.Email = new(Email)  // 带*号是指针型的, 所以要先初始化这个Address
	user.Email.CreateTime = "Email.CreateTime_002"
	user.Address.CreateTime = "Address.CreateTime_002"
	fmt.Printf("user=%#v\n createTime=%s,+++ %s\n",user,user.Email.CreateTime,user.Address.CreateTime)
}


func main(){
	test()
	test1()
	test2()
}

输出:

user=main.User{Username:"user01", Sex:"男", City:"黄冈", Age:18, AvatarUrl:"", Address:(*main.Address)(nil), Email:(*main.Email)(nil)} addr=(*main.Address)(nil)
user=main.User{Username:"user01", Sex:"男", City:"黄冈", Age:18, AvatarUrl:"", Address:(*main.Address)(nil), Email:(*main.Email)(nil)} addr="黄冈"
user=main.User{Username:"user01", Sex:"男", City:"", Age:18, AvatarUrl:"", Address:(*main.Address)(0xc0000b6330), Email:(*main.Email)(nil)}
 addr=&main.Address{Province:"湖北", City:"黄冈", CreateTime:""}
user=main.User{Username:"user01", Sex:"男", City:"", Age:18, AvatarUrl:"", Address:(*main.Address)(0xc0000b6390), Email:(*main.Email)(0xc000098440)}
 createTime=Email.CreateTime_002,+++ Address.CreateTime_002
posted @ 2022-03-13 23:45  ty1539  阅读(68)  评论(0编辑  收藏  举报