加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

append()表示在golang中只有一个切片字段

发布时间:2020-12-16 09:22:05 所属栏目:大数据 来源:网络整理
导读:我想将一个元素附加到一个只包含一个匿名切片的结构: package maintype List []Elementtype Element struct { Id string}func (l *List) addElement(id string) { e := Element{ Id: id,} l = append(l,e)}func main() { list := List{} list.addElement("t
我想将一个元素附加到一个只包含一个匿名切片的结构:

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 func.我有一个比这更好的方法,例如.让我保留List类型的第一个定义的一个?

非常感谢,sontags

解决方法

两个问题,

>您将* Element附加到[] Element,使用Element {}或将列表更改为[] * Element.
>您需要在addElement中取消引用切片.

Example:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读