-1
我想打電話給它接受界面在golang paramers切片的方法,但是我發現我無法通過它寫成這樣:如何在golang中調用接受slice接口的方法作爲參數?
type Base interface {
Run()
}
type A struct {
name string
}
func (a *A) Run() {
fmt.Printf("%s is running\n", a.name)
}
func foo1(b Base) {
b.Run()
}
func foo2(s []Base) {
for _, b := range s {
b.Run()
}
}
func TestInterface(t *testing.T) {
dog := &A{name: "a dog"}
foo1(dog)
// cat := A{name: "a cat"}
// foo1(cat)
s := []*A{dog}
foo2(s)
}
我得到的錯誤是這樣的:
cannot use s (type []*A) as type []Base in argument to foo2
FAQ:https://golang.org/doc/faq#convert_slice_of_interface – JimB