考虑这段代码:
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
结构的 slice 。在那个结构中,我有一段字符串和 bool 属性。首先,我调用 func1
函数来获取一些数据,然后遍历该 slice 并尝试在内部添加更多数据,但这段代码的输出是 [{[test1 test2] [] [] }]
bool 值在哪里?
我觉得问题出在 []TestCaseItem
因为它是一个保存值而不是指针的 slice ,也许我会错过某事。谁能解释一下?
最佳答案
您将 bool 值 append 到您的 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
}
或者您需要 append 到 slice 中 TestCaseItem
值的 Status
字段。
for i := range items {
items[i].Status = append(items[i].Status, false)
}
关于arrays - 将值 append 到 slice 的 slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46673797/