英文:
append() to stuct that only has one slice field in golang
问题
我想将一个只包含单个匿名切片的结构体添加一个元素:
package main
type List []Element
type Element struct {
Id string
}
func (l *List) addElement(id string) {
e := &Element{
Id: id,
}
*l = append(*l, e)
}
func main() {
list := List{}
list.addElement("test")
}
这样做是行不通的,因为addElement将l视为指向List的指针,而不是切片:
go run plugin.go
# command-line-arguments
./plugin.go:13: first argument to append must be slice; have *List
最有可能起作用的方法是这样:
type List struct {
elements []Element
}
然后相应地修复addElement函数。除此之外,是否有更好的方法,例如让我保留type List的第一个定义?
非常感谢,sontags
英文:
I want to append an element to a struct that only consists of a single annonymous slice:
package main
type List []Element
type Element struct {
Id string
}
func (l *List) addElement(id string) {
e := &Element{
Id: id,
}
l = append(l, e)
}
func main() {
list := List{}
list.addElement("test")
}
That does not work, since addElement does not know l as slice but as *List:
go run plugin.go
# command-line-arguments
./plugin.go:13: first argument to append must be slice; have *List
What most likely would work is to go like this:
type List struct {
elements []Element
}
and fix the addElement func accordingly. I there a nicer way than that, eg. one that let me keep the first definition of type List?
Many thanks, sontags
答案1
得分: 8
两个问题,
-
你正在将
*Element
追加到[]Element
中,要么使用Element{}
,要么将列表更改为[]*Element
。 -
你需要在
addElement
中取消引用切片。
示例:
func (l *List) addElement(id string) {
e := Element{
Id: id,
}
*l = append(*l, e)
}
英文:
Two problems,
-
You're appending
*Element
to[]Element
, either useElement{}
or change the list to[]*Element
. -
You need to dereference the slice in
addElement
.
func (l *List) addElement(id string) {
e := Element{
Id: id,
}
*l = append(*l, e)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论