Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go - append to slice in struct

Tags:

go

I am trying to implement 2 simple structs as follows:

package main  import (     "fmt" )  type MyBoxItem struct {     Name string }  type MyBox struct {     Items []MyBoxItem }  func (box *MyBox) AddItem(item MyBoxItem) []MyBoxItem {     return append(box.Items, item) }  func main() {      item1 := MyBoxItem{Name: "Test Item 1"}     item2 := MyBoxItem{Name: "Test Item 2"}      items := []MyBoxItem{}     box := MyBox{items}      AddItem(box, item1)  // This is where i am stuck      fmt.Println(len(box.Items)) } 

What am i doing wrong? I simply want to call the addItem method on the box struct and pass an item in

like image 750
Marty Wallace Avatar asked Aug 04 '13 11:08

Marty Wallace


People also ask

How do I append to a slice in Golang?

Since slices are dynamically-sized, you can append elements to a slice using Golang's built-in append method. The first parameter is the slice itself, while the next parameter(s) can be either one or more of the values to be appended.

Can you append a slice to a slice Golang?

append( ) function and spread operatorTwo slices can be concatenated using append method in the standard golang library.

Does append create a new slice?

The slice descriptor is composed of a pair of ints, one for len and one for cap, and a pointer to the underlying data. So, what append returns is indeed a new slice and what is passed to add option is indeed a copy of the slice descriptor.

How do you extend a structure in Golang?

Since Golang does not support classes, so inheritance takes place through struct embedding. We cannot directly extend structs but rather use a concept called composition where the struct is used to form other objects. So, you can say there is No Inheritance Concept in Golang.


1 Answers

Hmm... This is the most common mistake that people make when appending to slices in Go. You must assign the result back to slice.

func (box *MyBox) AddItem(item MyBoxItem) []MyBoxItem {     box.Items = append(box.Items, item)     return box.Items } 

Also, you have defined AddItem for *MyBox type, so call this method as box.AddItem(item1)

like image 134
ShuklaSannidhya Avatar answered Oct 01 '22 14:10

ShuklaSannidhya