(代码在http://play.golang.org/p/uuRKjtxs9D)
如果您打算对方法进行更改,则可能需要使用指针接收器。
// We also define a method Load on a FooList pointer receiver.
func (l *FooList) Load(a, b string) {
*l = append(*l, Foo{a, b})
}
但是,这有一个结果,即 FooList 值本身不会满足Loader接口。
var list FooList
Load(list) // You should see a compiler error at this point.
但是,指向 FooList 值的指针将满足Loader接口。
var list FooList
Load(&list)
完整代码如下:
package main
import "fmt"
/////////////////////////////
type Loader interface {
Load(string, string)
}
func Load(list Loader) {
list.Load("1", "2")
}
/////////////////////////////
type Foo struct {
a, b string
}
// We define a FooList to be a slice of Foo.
type FooList []Foo
// We also define a method Load on a FooList pointer receiver.
func (l *FooList) Load(a, b string) {
*l = append(*l, Foo{a, b})
}
// Given that we've defined the method with a pointer receiver, then a plain
// old FooList won't satisfy the Loader interface... but a FooList pointer will.
func main() {
var list FooList
Load(&list)
fmt.Println(list)
}