接口类型只是一组方法。请注意,接口定义的成员未指定接收方类型是否为指针。这是因为 值类型的方法集是其关联的指针类型的方法集的子集 。满嘴
我的意思是,如果您具有以下条件:
type Whatever struct { Name string}然后定义以下两种方法:
func (w *Whatever) Foo() { ...}func (w Whatever) Bar() { ...}然后类型
Whatever只有方法
Bar(),而类型
*Whatever只有方法
Foo()和
Bar()。这意味着如果您具有以下界面:
type Grits interface { Foo() Bar()}然后
*Whatever执行
Grits但
Whatever不执行,因为
Whatever缺少方法
Foo()。当您将函数的输入定义为接口类型时,您不知道它是指针还是值类型。
下面的示例说明了同时采用两种接口类型的函数:
package mainimport "fmt"type Fruit struct { Name string}func (f Fruit) Rename(name string) { f.Name = name}type Candy struct { Name string}func (c *Candy) Rename(name string) { c.Name = name}type Renamable interface { Rename(string)}func Rename(v Renamable, name string) { v.Rename(name) // at this point, we don't know if v is a pointer type or not.}func main() { c := Candy{Name: "Snickers"} f := Fruit{Name: "Apple"} fmt.Println(f) fmt.Println(c) Rename(f, "Zemo Fruit") Rename(&c, "Zemo Bar") fmt.Println(f) fmt.Println(c)}你可以调用
Raname(&f, "Jorelli Fruit"),但不能
Rename(c, "JorelliBar"),因为这两个
Fruit和
*Fruit实施
Renamable,而
*Candy工具
Renable和
Candy没有。
http://play.golang.org/p/Fb-L8Bvuwj



