Go - 追加到struct中的切片

Mar*_*ace 26 go

我试图实现2个简单的结构如下:

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))
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?我只想在box结构上调用addItem方法并传入一个项目

Shu*_*hya 50

嗯......这是人们在Go中附加切片时最常犯的错误.您必须将结果分配回切片.

func (box *MyBox) AddItem(item MyBoxItem) []MyBoxItem {
    box.Items = append(box.Items, item)
    return box.Items
}
Run Code Online (Sandbox Code Playgroud)

此外,您已AddItem*MyBox类型定义,因此请将此方法称为box.AddItem(item1)


zzz*_*zzz 12

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))
}
Run Code Online (Sandbox Code Playgroud)

操场


输出:

1
Run Code Online (Sandbox Code Playgroud)


arj*_*era 11

虽然这两个答案都很好。还有两个变化可以做,

  1. 摆脱 return 语句,因为该方法被调用以获取指向结构的指针,因此切片会自动修改。
  2. 无需初始化空切片并将其分配给结构
    package main    

    import (
        "fmt"
    )

    type MyBoxItem struct {
        Name string
    }

    type MyBox struct {
        Items []MyBoxItem
    }

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


    func main() {

        item1 := MyBoxItem{Name: "Test Item 1"}
        item2 := MyBoxItem{Name: "Test Item 2"}

        box := MyBox{}

        box.AddItem(item1)
        box.AddItem(item2)

        // checking the output
        fmt.Println(len(box.Items))
        fmt.Println(box.Items)
    }
Run Code Online (Sandbox Code Playgroud)