【问题标题】:append() to stuct that only has one slice field in golangappend() 到在 golang 中只有一个 slice 字段的结构
【发布时间】:2014-09-03 18:25:47
【问题描述】:

我想将一个元素附加到一个只包含一个匿名切片的结构中:

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 是 slice 而是 *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 函数。我有比这更好的方法,例如。让我保留类型 List 的第一个定义?

非常感谢,歌曲标签

【问题讨论】:

    标签: go


    【解决方案1】:

    两个问题,

    1. 您将*Element 附加到[]Element,使用Element{} 或将列表更改为[]*Element

    2. 您需要取消引用addElement 中的切片。

    Example

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

    【讨论】:

    • go run plugin.go # command-line-arguments ./plugin.go:15: cannot use append(*l, e) (type []Element) as type List in assignment
    猜你喜欢
    • 2017-11-12
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多