This is a creation in Article, where the information may have evolved or changed.
PackageMainImport "FMT"/* struct in struct struct-go is very similar to struct in C, and go does not class-use type <Name> struct{} to define structure, Names follow visibility rules-support for pointer-type members to themselves-supports anonymous structures, can be used as member-defined member variables-anonymous structures can also be used for map values-literals can be used to initialize structures-allowing direct reading and writing of struct members directly through pointers-members of the same type can make direct copy copy-support = = with! = operator, but does not support > or <-support your Name field, which is essentially defined by a type name as the domain-embedded structure as your name field looks like inheritance, but not inheritance-can use your Name field pointer */typePersonstruct{NamestringAgeint}typePerson_tempstruct{NamestringAgeintContactstruct{Phone, Citystring}//Nested anonymous structure}funcMain () {A: = person{} a.age = -A.name ="Joe"B: = person{Name:"Joe", Age: +, }//Initialization of literalsA (&a) fmt. Println ("------") FMT. Println (b) fmt. Println ("------") c: = person_temp{} c.age = -C.name ="Lihuidi"C.contact.city ="Handan"C.contact.phone ="15684505257" //initialization method for structures with nested anonymous structuresFmt. Println (c) fmt. Println ("------") FMT. Println (A = = b)//Determine if A and B are equal}funcA (per *person) {FMT. Println ("A", per)}//Structure support anonymous structure
PackageMainImport "FMT"typeHumanstruct{Sexint}typeTeacherstruct{Human NamestringAgeint}typeStudentstruct{Human//The structure name is essentially used as the field nameNamestringAgeint}//Embedding of StructuresfuncMain () {A: = Teacher{name:"Joe", Age: +, Human:human{sex:1}}//Operation Method! B: = Student{name:"Joe", Age: -, Human:human{sex:0}}//Please remember this operation Method! A.name ="Joe2"A.age = +A.sex =0 //visible, all the variables are in the new structure after embedding.Fmt. Println (A, B)}
package mainimport ( "fmt")typestruct { B string}typestruct { string}func main() { "A""B"}} //成功取到了同名字段,如果最高级不存在Name,会自动往下找,知道找到Name}