当前位置: 首页 > 知识库问答 >
问题:

Go-附加到结构中的切片

沈博达
2023-03-14

我试图实现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方法并传入一个项

共有3个答案

杭涵映
2023-03-14

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

  1. 当为指向结构的指针调用方法时,去掉return语句,因此切片会自动修改
    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)
    }
章涵容
2023-03-14
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))
}

游戏场

输出:

1
微生昌勋
2023-03-14

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

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

另外,您已经为*MyBox类型定义了AddItem,因此将此方法称为box。附加项(第1项)

 类似资料:
  • 问题内容: 我正在尝试实现2个简单的结构,如下所示: 我究竟做错了什么?我只想在框结构上调用addItem方法并在其中传递一个项目 问题答案: 嗯…这是人们在Go中附加到切片时最常犯的错误。您必须将结果分配回slice。 另外,您已经定义了类型,因此将该方法称为

  • 我试图理解如何在Go中操作数据结构,以及它指向指针(带有副本或引用)的方法。 我的代码在Go Playground这里:https://play.golang.org/p/j_06RS5Xcz 我制作了一个结构的切片图,里面还有一个其他东西的切片。 在这里: 我想在以后的程序中附加其他项。似乎我必须使用指针来解决这个问题,但我不知道如何解决。 我的实体应该是这样吗? 如果是这样的话,我应该如何向它

  • 以下代码的输出令我惊讶: 在操场上运行时(https://play.golang.org/p/Ph67tHOt2Z_I)输出如下: 我相信我对切片的处理是正确的;据我所知,它在NewThing()中被初始化为nil,并在Add()中被追加(确保从append返回的值只分配给它的第一个参数)。 我错过了一些非常明显的东西吗? 我查看了以下资源以获得解释: https://gobyexample.co

  • 问题内容: 因此,我可以像这样从本地文件中读取: 而且我可以写入本地文件 但是,如何追加文件?有内置方法吗? 问题答案: 此答案在Go1中有效:

  • 问题内容: 组装传递给GRMustache.swift的数据有效载荷以渲染胡子模板时,我处于一种需要将数据附加到先前在字典中定义的数组的场景中。 我的数据结构开始于: 该密钥对是一家集我需要一个循环内后追加。 要添加到数组中,我正在尝试类似的方法: 此错误,因为type的值没有成员,并且二进制运算符不能应用于type 和的操作数。 这很有意义,因为我需要强制转换要附加的值。但是,我不能改变数组。

  • 问题内容: 我正在看Go,它看起来很有前途。我试图弄清楚如何获得go结构的大小,例如 我当然知道它是24字节,但是我想以编程方式知道它。 您对如何执行此操作有任何想法吗? 问题答案: 注意: OP错误。unsafe.Sizeof确实在示例Coord3d结构上返回24。请参阅下面的评论。