去 - 在结构中追加切片 [英] Go - append to slice in struct

查看:94
本文介绍了去 - 在结构中追加切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  package main 

import(
fmt


类型MyBoxItem结构{
名称字符串
}

类型MyBox结构{
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 }
$ b $ item:= [] MyBoxItem {}
box:= MyBox {items}
$ b $ AddItem(box,item1)//这是我的位置卡住

fmt.Println(len(box.Items))
}

我做错了什么?我只是想调用box结构体上的addItem方法,并在

解决方案

中输入一个项目。嗯......这是最在Go中追加切片时人们犯的常见错误。
$ b

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

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


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

解决方案

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)

这篇关于去 - 在结构中追加切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆