【问题标题】:Go - append to slice in structGo - 追加到结构中的切片
【发布时间】:2013-08-05 05:34:07
【问题描述】:

我正在尝试实现 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))
}

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

【问题讨论】:

    标签: go


    【解决方案1】:

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

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

    另外,你已经为*MyBox类型定义了AddItem,所以将此方法称为box.AddItem(item1)

    【讨论】:

      【解决方案2】:
      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
      

      【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2018-12-05
        • 1970-01-01
        • 2017-07-27
        • 2019-11-05
        • 2016-07-22
        • 2016-12-08
        • 2014-04-02
        • 1970-01-01
        • 2019-01-28
        相关资源
        最近更新 更多