将元素追加到结构体切片中。

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

Go appending elements to slice of struct

问题

我正在尝试将元素添加到结构体切片中,但是返回了错误"invalidAppend",这意味着我传递的第一个参数不是切片。

这是代码:

  1. type Item struct {
  2. Attr string
  3. }
  4. type ItemsList []Item
  5. type IItemsList interface {
  6. GetItemsList() ItemsList
  7. AddItem(Item)
  8. }
  9. func NewItemsList() IItemsList {
  10. return &ItemsList{}
  11. }
  12. func (il *ItemsList) GetItemsList() ItemsList {
  13. return *il
  14. }
  15. func (il *ItemsList) AddItem(i Item) {
  16. *il = append(*il, i)
  17. }

我无法确定正确的操作方式。

英文:

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.

Link to Go Playground.

Here's the code:

  1. type Item struct {
  2. Attr string
  3. }
  4. type ItemsList []Item
  5. type IItemsList interface {
  6. GetItemsList() ItemsList
  7. AddItem(Item)
  8. }
  9. func NewItemsList() IItemsList {
  10. return &ItemsList{}
  11. }
  12. func (il *ItemsList) GetItemsList() ItemsList {
  13. return *il
  14. }
  15. func (il *ItemsList) AddItem(i Item) {
  16. il = append(il, i)
  17. }

I can't figure how is the correct way to proceed with this append.

答案1

得分: 1

"我传递的第一个参数不是一个切片"

第一个参数是一个指向切片的指针。

  1. type ItemsList []Item
  2. func (il *ItemsList) AddItem(i Item) {
  3. il = append(il, i)
  4. }

第一个参数是一个切片。

  1. func (il *ItemsList) AddItem(i Item) {
  2. *il = append(*il, i)
  3. }

https://go.dev/play/p/Se2ZWcucQOp


Go编程语言规范

地址运算符

对于指针类型 *T 的操作数 x,指针间接引用 *x 表示由 x 指向的类型为 T 的变量。

英文:

> the first argument I'm passing is not a slice

The first argument is a pointer to a slice.

  1. type ItemsList []Item
  2. func (il *ItemsList) AddItem(i Item) {
  3. il = append(il, i)
  4. }

The first argument is a slice.

  1. func (il *ItemsList) AddItem(i Item) {
  2. *il = append(*il, i)
  3. }

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.

huangapple
  • 本文由 发表于 2022年12月26日 04:40:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/74915781.html
匿名

发表评论

匿名网友

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

确定