英文:
Go appending elements to slice of struct
问题
我正在尝试将元素添加到结构体切片中,但是返回了错误"invalidAppend",这意味着我传递的第一个参数不是切片。
这是代码:
type Item struct {
Attr string
}
type ItemsList []Item
type IItemsList interface {
GetItemsList() ItemsList
AddItem(Item)
}
func NewItemsList() IItemsList {
return &ItemsList{}
}
func (il *ItemsList) GetItemsList() ItemsList {
return *il
}
func (il *ItemsList) AddItem(i Item) {
*il = append(*il, i)
}
我无法确定正确的操作方式。
英文:
I'm trying to append elements to a slice of a struct but it's returning error invalidAppend, that means that the first argument I'm passing is not a slice.
Here's the code:
type Item struct {
Attr string
}
type ItemsList []Item
type IItemsList interface {
GetItemsList() ItemsList
AddItem(Item)
}
func NewItemsList() IItemsList {
return &ItemsList{}
}
func (il *ItemsList) GetItemsList() ItemsList {
return *il
}
func (il *ItemsList) AddItem(i Item) {
il = append(il, i)
}
I can't figure how is the correct way to proceed with this append.
答案1
得分: 1
"我传递的第一个参数不是一个切片"
第一个参数是一个指向切片的指针。
type ItemsList []Item
func (il *ItemsList) AddItem(i Item) {
il = append(il, i)
}
第一个参数是一个切片。
func (il *ItemsList) AddItem(i Item) {
*il = append(*il, i)
}
https://go.dev/play/p/Se2ZWcucQOp
地址运算符
对于指针类型 *T 的操作数 x,指针间接引用 *x 表示由 x 指向的类型为 T 的变量。
英文:
> the first argument I'm passing is not a slice
The first argument is a pointer to a slice.
type ItemsList []Item
func (il *ItemsList) AddItem(i Item) {
il = append(il, i)
}
The first argument is a slice.
func (il *ItemsList) AddItem(i Item) {
*il = append(*il, i)
}
https://go.dev/play/p/Se2ZWcucQOp
> The Go Programming Language Specification
>
> Address operators
>
> For an operand x of pointer type *T, the pointer indirection *x denotes the variable of type T pointed to by x.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论