dsqbh42082 2014-07-13 19:19
浏览 76
已采纳

append()到在golang中只有一个slice字段的结构

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条回答 默认 最新

  • douhui4699 2014-07-13 19:23
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?