我append在 Go 中调用函数时遇到问题
type Dog struct {
color string
}
type Dogs []Dog
Run Code Online (Sandbox Code Playgroud)
我想将“狗”附加到“狗”中。
我试过这样做
Dogs = append(Dogs, Dog)
Run Code Online (Sandbox Code Playgroud)
但我收到这个错误
First argument to append must be slice; have *Dogs
Run Code Online (Sandbox Code Playgroud)
编辑:另外,例如,如果我想检查这条狗是否包含颜色“白色”。我怎么称呼这个?
if Dog.color.contains("white") {
//then append this Dog into Dogs
}
Run Code Online (Sandbox Code Playgroud)
正如朋友所说,它不应该是一种类型,以下示例可能会有所帮助:
// 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15070 次 |
| 最近记录: |