Go - append to slice in struct

后端 未结 3 1553
别跟我提以往
别跟我提以往 2020-12-25 11:55

I am trying to implement 2 simple structs as follows:

package main

import (
    \"fmt\"
)

type MyBoxItem struct {
    Name string
}

type MyBox struct {
           


        
3条回答
  •  被撕碎了的回忆
    2020-12-25 12:49

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

    Playground


    Output:

    1
    

提交回复
热议问题