Append elements to a struct slice

王林
Release: 2024-02-09 14:57:18
forward
804 people have browsed it

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!

Question content

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)
}
Copy after login

I don't know the correct way how to do this append operation.

Solution

The 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)
}
Copy after login

The first parameter is a slice.

func (il *ItemsList) AddItem(i Item) {
    *il = append(*il, i)
}
Copy after login

https://www.php.cn/link/97fc9b260a90d9c0aca468d2e6536980

go Programming Language Specification

Address Operator

For 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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!