【发布时间】:2013-09-14 21:33:45
【问题描述】:
我很难理解指针、切片和接口在 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 切片添加了一个元素,但仅此而已。 Load 中的 list 仍然是 nil。我想我应该能够将引用传递给我的切片并附加一些东西。不过,我显然错过了如何让它工作的东西。
【问题讨论】: