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

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

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

问题

我想将一个只包含单个匿名切片的结构体添加一个元素:

  1. package main
  2. type List []Element
  3. type Element struct {
  4. Id string
  5. }
  6. func (l *List) addElement(id string) {
  7. e := &Element{
  8. Id: id,
  9. }
  10. *l = append(*l, e)
  11. }
  12. func main() {
  13. list := List{}
  14. list.addElement("test")
  15. }

这样做是行不通的,因为addElement将l视为指向List的指针,而不是切片:

  1. go run plugin.go
  2. # command-line-arguments
  3. ./plugin.go:13: first argument to append must be slice; have *List

最有可能起作用的方法是这样:

  1. type List struct {
  2. elements []Element
  3. }

然后相应地修复addElement函数。除此之外,是否有更好的方法,例如让我保留type List的第一个定义?

非常感谢,sontags

英文:

I want to append an element to a struct that only consists of a single annonymous slice:

  1. package main
  2. type List []Element
  3. type Element struct {
  4. Id string
  5. }
  6. func (l *List) addElement(id string) {
  7. e := &Element{
  8. Id: id,
  9. }
  10. l = append(l, e)
  11. }
  12. func main() {
  13. list := List{}
  14. list.addElement("test")
  15. }

That does not work, since addElement does not know l as slice but as *List:

  1. go run plugin.go
  2. # command-line-arguments
  3. ./plugin.go:13: first argument to append must be slice; have *List

What most likely would work is to go like this:

  1. type List struct {
  2. elements []Element
  3. }

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 中取消引用切片。

示例

  1. func (l *List) addElement(id string) {
  2. e := Element{
  3. Id: id,
  4. }
  5. *l = append(*l, e)
  6. }
英文:

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:

  1. func (l *List) addElement(id string) {
  2. e := Element{
  3. Id: id,
  4. }
  5. *l = append(*l, e)
  6. }

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:

确定