我在围绕Go如何交互指针,切片和接口方面遇到了困难。这是我目前已经编写了:通过引用传递自定义切片类型
type Loader interface {
Load(string, string)
}
type Foo struct {
a, b string
}
type FooList []Foo
func (l FooList) Load(a, b string) {
l = append(l, Foo{a, b})
// l contains 1 Foo here
}
func Load(list Loader) {
list.Load("1", "2")
// list is still nil here
}
鉴于此设置,然后我试着做到以下几点:
var list FooList
Load(list)
fmt.Println(list)
然而,列表始终是nil
这里。我的FooList.Load函数确实会将一个元素添加到l
切片,但这是尽可能多的。负载中的list
继续为nil
。我想我应该能够通过我的切片的参考,并附加到它的东西。我明显错过了如何让它工作。
我发誓,这是我开始,但得到类型错误。然后,我读了一些地方,你不应该把指针指向片,因为它们已经是引用,这就是我感到困惑的地方......无论如何,现在它都可以工作。谢谢! – Bill