Tag:main ack unc Pointer ddr add type new structural body
Code_016_struct_anonymous_field2 Project Main.gopackage mainimport ("FMT") type person struct {name string sex byte AG E int}type Student struct {Person id int addr String name string//same name field}type mystr string//Custom type ' Student01 struct { person int Mystr}type Person02 struct {name string sex byte int}type Student02 struct {*person02//anonymous field, struct pointer id int Addr String}func Main () {//1) uses var s Student s.name = "Ck_god"//default to the outermost member assignment FMT. Printf ("%+v\n", s) s.person.name = "God_girl"//Display call FMT. Printf ("%+v\n", s)//2) Other anonymous fields S1: = student01{person{"Ck_god", 1, 1, "wz"} fmt. Printf ("%+v\n", S1)//non-struct type of anonymous member Operation FMT. Printf ("%s,%c,%d,%d,%s\n", S1.name, S1.sex, S1.age, S1.int, s1.mystr)//3) struct pointer type s3: = student02{&person02{"Ck_god ", 0, 1," BJ "} fmt. Printf ("%+v\n", S3) Fmt. Printf ("%s,%c,%d\n", S3.name, S3.sex, s3.age) var s2 Student02 S2. PERSON02 = new (PERSON02)//Allocated Space S2.name = "ck" S2.sex = 1 s2.age = S2.id = 2 s2.addr = "sz" FMT. Println (S2.name, S2.sex, S2.agE, S2.id, S2.age)}
The output results are as follows:
{Person:{name: sex:0 age:0} id:0 addr: name:ck_god}{Person:{name:god_girl sex:0 age:0} id:0 addr: name:ck_god}{Person:{name:ck_god sex:1 age:18} int:1 mystr:wz}ck_god,,18,1,wz{Person02:0xc000004480 id:1 addr:bj}ck_god,,18ck 1 20 2 20
Anonymous field of "inherited" struct in go 2