我在Go
中调用append
函数时遇到问题
type Dog struct {
color string
}
type Dogs []Dog
我想追加" Dog"进入"狗"。
我试过这个
Dogs = append(Dogs, Dog)
但是我收到了这个错误
First argument to append must be slice; have *Dogs
对不起,我是Go的新手。
谢谢!
编辑: 此外,如果我想检查这只狗是否包含颜色"白色",例如。我怎么称呼这个?
if Dog.color.contains("white") {
//then append this Dog into Dogs
}
答案 0 :(得分:4)
狗是一种不是变量的类型,你可能想:
var Dogs []Dog
答案 1 :(得分:4)
正如朋友所说,它不应该是一种类型,这里的示例可能会有所帮助:
// 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)