Struct
nil 指针
package mainimport ("fmt")type Encoder struct{name string}func (e *Encoder) Encode() error {if e == nil {e = &Encoder{"nil"}}fmt.Println("Encoder name:", e.name)return nil}func main() {var e *Encodere.Encode()}// Encoder name: nil
Interface
package mainimport ("fmt")type Coder interface {Encode() error}type Encoder struct {name string}func (e *Encoder) Encode() error {if e == nil {e = &Encoder{"nil"}}fmt.Println("Encoder name:", e.name)return nil}func main() {//⚠️attention: CodeMan's Type is interfacevar CodeMan Coder = &Encoder{"man"}CodeMan.Encode()// CodeWomen's Type is structvar CodeWomen *Encoder = &Encoder{"woman"}CodeWomen.Encode()}// Encoder name: man// Encoder name: woman
Embed
by @fengyfei(fengyfei) @Abser(杨鼎睿)(abser) from GitHub
Anonymous Call
package mainimport ("fmt")type Anyg struct {}func (a *Anyg) Any() {fmt.Println("Any:any")}type Someg struct{}func (a *Someg) Some() {fmt.Println("Some:some")}type All struct{}func (a *All) Any() {fmt.Println("All:any")}func (a *All) Some() {fmt.Println("All:some")}// a struct include these sturct which have same name methodstype Collection struct {Somegp AllAnyg}func (c *Collection) Any(){fmt.Println("collection:any")}func (c *Collection) Some() {fmt.Println("collection:some")}// Documents some line to test.// Then know how can use embed struct.func main(){c := &Collection{Someg{},All{},Anyg{},}c.Any()c.Some()c.p.Any()c.p.Some()}// <---output--->// collection:any// collection:some// All:any// All:some
Embed to implement Interface
package mainimport ("fmt")// Let's learn this skills how to work in RealWorld// Type a interface first.type Ready interface {Any()Some()Readiness() bool}// There is a struct implements Readytype AlwaysReady struct{}func (a *AlwaysReady)Any() {}func (a *AlwaysReady)Some() {}func (a *AlwaysReady) Readiness()bool {return true}// We use All struct to implements our own methods logic.// and use AlwaysReady to implement Ready interface.type RealWorldUse struct{p AllAlwaysReady}func EmbedInRealWorld(embedReady Ready){fmt.Println(embedReady.Readiness())}func main() {embed := &RealWorldUse{All{},AlwaysReady{},}EmbedInRealWorld(embed)}// <---output--->// true
