我熟悉 Go 中,界面定义功能,而不是数据。您将一组方法放入界面中,但您无法指定界面所需的任何字段。 ! @$ b# q/ f' I. C3 z9 l例如: / ^) k3 v4 q" e1 a% w4 y( t
// Interfacetype Giver interface Give() int64}// One implementationtype FiveGiver struct {}func (fg *FiveGiver) Give() int64 return 5}// Another implementationtype VarGiver struct number int64}func (vg *VarGiver) Give() int64 return vg.number} , u# R0 S, L% a9 X
现在我们可以使用接口及其实现: ( R9 j, P/ X$ P
// A function that uses the interfacefunc GetSomething(aGiver Giver) fmt.Println("The Giver gives: ",aGiver.Give()}// Bring it all togetherfunc main() fg := &FiveGiver{} vg := &VarGiver{3} GetSomething(fg) GetSomething(vg)}/*Resulting output:53*/ # `! r: [3 |1 a3 M. d3 E9 v
现在,你不能做这样的事: 0 K9 j' q9 W9 e/ f; }2 [
type Person interface Name string Age int64}type Bob struct implements Person { // Not Go syntax! ...}func PrintName(aPerson Person) fmt.Println("erson's name is: ",aPerson.Name)}func main() b := &Bob{"Bob",23} PrintName(b)}, v. f- k7 Z: v; e$ X# w
然而,在玩了界面和嵌入式结构后,我找到了一种时尚的方法来做到这一点:1 E2 a& v8 k9 s Y. ^/ n8 M. r. k
type PersonProvider interface GetPerson() *Person}type Person struct Name string Age int64}func (p *Person) GetPerson() *Person return p}type Bob struct FavoriteNumber int64 Person} 9 c! Y. `8 H p/ _1 H j0 x Y0 p
结构体嵌入,Bob 拥有 Person 的一切。它还实现了 PersonProvider 接口,所以我们可以Bob 传递给使用该接口的函数。 ) A, [0 ?" @$ e