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
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.
append( ) function and spread operatorTwo slices can be concatenated using append method in the standard golang library.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With