【问题标题】:append value to slice of a slice将值附加到切片的切片
【发布时间】:2017-10-10 18:44:20
【问题描述】:

考虑这段代码:

func main() {
    items := func1()

    for _, v := range items {
        v.Status = append(v.Status, false)
    }

    fmt.Println(items)

}

//TestCaseItem represents the test case
type TestCaseItem struct {
    Actual   []string
    Expected []string
    Status   []bool
}

func func1() []TestCaseItem {
    var tc = make([]TestCaseItem, 0)

    var item = &TestCaseItem{}
    item.Actual = append(item.Actual, "test1")
    item.Actual = append(item.Actual, "test2")

    tc = append(tc, *item)

    return tc
}

我有一个 TestCaseItem 结构类型的切片。在那个结构中,我有一部分字符串和布尔属性。首先我调用func1 函数来获取一些数据,然后遍历该切片并尝试在其中追加更多数据,但是这段代码的输出是[{[test1 test2] [] []}] 布尔值在哪里?

我觉得问题出在[]TestCaseItem 因为它是一个保存值而不是指针的切片,也许我会错过某事。有人可以解释一下吗?

【问题讨论】:

    标签: arrays go append


    【解决方案1】:

    您将布尔值附加到您的 TestCaseItems 的副本中。

    您要么需要使用指向项目的指针:

    func func1() []*TestCaseItem {
        var tc = make([]*TestCaseItem, 0)
    
        var item = &TestCaseItem{}
        item.Actual = append(item.Actual, "test1")
        item.Actual = append(item.Actual, "test2")
    
        tc = append(tc, item)
    
        return tc
    }
    

    或者您需要附加到切片中TestCaseItem 值的Status 字段。

    for i := range items {
        items[i].Status = append(items[i].Status, false)
    }
    

    【讨论】:

    • 是的,这是真的,但据我所知,它们都是切片,切片是对底层数组的引用,但在这种情况下,它们没有引用为什么?
    • @kyur:它与切片本身中的指针没有任何关系,您正在复制 TestCaseItem 值,这意味着您没有写入相同的切片值。
    猜你喜欢
    • 1970-01-01
    • 2016-10-20
    • 2015-11-09
    • 2020-07-09
    • 1970-01-01
    • 2015-11-03
    • 2017-08-11
    • 2019-12-30
    • 2015-10-16
    相关资源
    最近更新 更多