append的第一个参数必须是切片类型。

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

First argument to append must be slice

问题

我在调用Go中的append函数时遇到了问题。

type Dog struct {
    color string
}

type Dogs []Dog

我想将"Dog"追加到"Dogs"中。

我尝试了以下代码:

Dogs = append(Dogs, Dog)

但是我得到了以下错误:

First argument to append must be slice; have *Dogs

另外,如果我想检查这个Dog是否包含颜色"white",我该如何调用?

if Dog.color.contains("white") {
    //然后将这个Dog追加到Dogs中
}
英文:

I am having trouble calling the append function in Go

type Dog struct {
	color  string
}

type Dogs []Dog

I want to append "Dog" into "Dogs".

I tried doing this

Dogs = append(Dogs, Dog)

But I get this error

First argument to append must be slice; have *Dogs

Edit:
Also, if I want to check if this Dog contains the color "white", for example. How would I call this?

 if Dog.color.contains("white") { 
    //then append this Dog into Dogs
 }

答案1

得分: 7

根据朋友的说法,这不应该是一个类型,下面是一个有用的示例:

// 创建一个空的结构体指针切片。
Dogs := []*Dog{}
// 创建结构体并将其添加到切片中。
dog := new(Dog)
dog.color = "black"
Dogs = append(Dogs, dog)

英文:

As friends says it should not be a type, here is example can be helpful:

// Create empty slice of struct pointers.
Dogs := []*Dog{}
// Create struct and append it to the slice.
dog := new(Dog)
dog.color = "black"
Dogs = append(Dogs, dog)

答案2

得分: 5

Dogs是一种类型而不是一个变量,你可能想要的是:

var Dogs []Dog
英文:

Dogs is a type not a variable, you probably meant to:

var Dogs []Dog

huangapple
  • 本文由 发表于 2017年2月5日 18:48:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/42051117.html
匿名

发表评论

匿名网友

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

确定