Home > Article > Backend Development > Append elements to a struct slice
php Xiaobian Youzi is here to introduce you to a cool technique - attaching elements to structure slices. Struct slice is a data structure used in Golang. It can store different types of elements and has the ability to dynamically expand. By appending elements to struct slices, we can easily extend and manipulate data collections, enabling more flexible and efficient programming. Let's take a look at how to use this technique to improve our programming skills!
I'm trying to append an element to a slice of a struct, but it returns the error invalidappend, which means that I passed The first parameter is not a slice.
Link to go playground.code show as below:
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 don't know the correct way how to do this append operation. SolutionThe first parameter I passed is not a slice
The first parameter is a pointer to the slice.
type itemslist []item func (il *itemslist) additem(i item) { il = append(il, i) }The first parameter is a slice.
func (il *ItemsList) AddItem(i Item) { *il = append(*il, i) }
https://www.php.cn/link/97fc9b260a90d9c0aca468d2e6536980
go Programming Language Specification
Address OperatorFor the operand x of pointer type *t, pointer indirect addressing *x represents the variable of type t pointed to by x.
The above is the detailed content of Append elements to a struct slice. For more information, please follow other related articles on the PHP Chinese website!