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

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

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.

Link to Go Playground.

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


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.

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.

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:

确定