append() to stuct that only has one slice field in golang

huangapple go评论91阅读模式
英文:

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

两个问题,

  1. 你正在将 *Element 追加到 []Element 中,要么使用 Element{},要么将列表更改为 []*Element

  2. 你需要在 addElement 中取消引用切片。

示例

func (l *List) addElement(id string) {
    e := Element{
        Id: id,
    }
    *l = append(*l, e)
}
英文:

Two problems,

  1. You're appending *Element to []Element, either use Element{} or change the list to []*Element.

  2. You need to dereference the slice in addElement.

Example:

func (l *List) addElement(id string) {
    e := Element{
        Id: id,
    }
    *l = append(*l, e)
}

huangapple
  • 本文由 发表于 2014年7月14日 03:19:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/24726341.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定