在Go语言中,如何向结构体中的切片添加元素?

60

我正在尝试实现以下两个简单的结构体:

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))
}

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

3个回答

110

嗯... 这是在 Go 中添加到切片时人们最常犯的错误。必须将结果赋回到切片。

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

此外,您已经为*MyBox类型定义了AddItem方法,因此请使用box.AddItem(item1)调用此方法。


21
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


输出:

1

你为什么需要这行代码 - items := []MyBoxItem{}?请参考此代码 - https://play.golang.org/p/7oq5qUuzypU。 - Rahul Satal

18

虽然这两个答案都没问题。有两个改变可以做:

  1. 去掉返回语句,因为该方法是针对结构体指针调用的,所以切片会自动修改。
  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)
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接