go 结构体嵌套结构体指针,必须先初始化指针结构体,才能赋值
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("00 user=%#v addr=%#v\n",user,user.Address)
fmt.Printf("01 user=%#v addr=%#v\n",user,user.City)
}
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("02 user=%#v\n",user)
fmt.Printf("03 EmailCreateTime=%s\n",user.Email.CreateTime)
fmt.Printf("04 AddressCreateTime=%s,\n",user.Address.CreateTime)
fmt.Printf("05 Address=%s,\n",user.Email)
fmt.Printf("06 Email=%s,\n",user.Address)
}
func main(){
test()
test2()
}
输出;
00 user=main.User{Username:"user01", Sex:"男", City:"黄冈", Age:18, AvatarUrl:"", Address:(*main.Address)(nil), Email:(*main.Email)(nil)} addr=(*main.Address)(nil)
01 user=main.User{Username:"user01", Sex:"男", City:"黄冈", Age:18, AvatarUrl:"", Address:(*main.Address)(nil), Email:(*main.Email)(nil)} addr="黄冈"
02 user=main.User{Username:"user01", Sex:"男", City:"", Age:18, AvatarUrl:"", Address:(*main.Address)(0xc00006c330), Email:(*main.Email)(0xc000004480)}
03 EmailCreateTime=Email.CreateTime_002
04 AddressCreateTime=Address.CreateTime_002,
05 Address=&{ Email.CreateTime_002},
06 Email=&{湖北 黄冈 Address.CreateTime_002},
写入自己的博客中才能记得长久