英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论