This is a creation in Article, where the information may have evolved or changed.
Hot code's coming in.
Package Mainimport"FMT"/*inheriting one struct into another struct, known as the difference between combinatorial anonymity and composition if a struct nested another anonymous struct, the struct can directly access the anonymous struct's method, enabling inheritance if a struct nested another "well-known" struct, So this pattern is called a combination. If a struct is nested with multiple anonymous structs, the struct can directly access multiple anonymous struct methods to achieve multiple inheritance*/type Carstruct{weightintnamestring}func (P*Car) Run () {fmt. Println ("Running")}type Bikestruct{Car Lunziint}type Trainstruct{Car}func (P*train) String ()string{str:= Fmt. Sprintf ("name=[%s] weight=[%d]", P.name, P.weight)returnStr}func Main () {vara Bike a.weight= -A.name="Bike"A.lunzi=2FMT. Println (a) a.run ()varb Train b.weight= -B.name="Train"B.run () fmt. Printf ("%s", &b)}
Exercise 2
Package Mainimport ("FMT" " Time") Type Carstruct{Namestring Ageint}func (c*car) Set (namestring, ageint) {C.name=name C.age=Age}type Car2struct{Namestring}//Go has anonymous field attributesType Trainstruct{Car Car2 createtime time. time//count int is normal and the Go feature can be written as int}//to the train method, T specifies the name of the accepted variable, which can be called This,t,pFunc (t *train) Set (ageint) {T.int=Age}func Main () {vartrain train train.int= - //the anonymous field is used here to write an age assignment//(&train). Set (+)Train. Car.set ("Huas", -) train. Car.name="Test" //here name must specify structFMT. PRINTLN (train)}