consider this piece of code:
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
}
i have an slice of type TestCaseItem
struct. In that struct i have slice of string and bool properties. first i call func1
function to grab some data and then iterate over that slice and try to append more data insdide, but the output of this code is [{[test1 test2] [] []}]
where are the booleans ?
i feel like the problem is []TestCaseItem
cuz its a slice that holds values rather than pointers and maybe i'll miss sth. can anybody explain this?
You're appending the bool values to copies of your TestCaseItems.
You either need to use a pointer to the items:
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
}
Or you need to append to the Status
field of the TestCaseItem
value that's in the slice.
for i := range items {
items[i].Status = append(items[i].Status, false)
}