2017-10-10 139 views
0

考慮這一段代碼的:追加值到切片的切片

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因爲它是一個容納值而不是指針的切片,也許我會想念某事。有人可以解釋這一點嗎?

回答

0

您正在將bool值附加到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) 
} 
+0

是的,這是真的,但所有這些都是切片,據我所知切片是對底層數組的引用,但在這種情況下,他們不引用這是爲什麼? – afrikaan

+0

@kyur:它與片本身中的指針沒有任何關係,您正在複製'TestCaseItem'值,這意味着您沒有寫入相同的片值。 – JimB