最近項目中有遇到相似問題,作個記錄。segmentfault
舉個例子,[5]int爲數組,[]int爲slice(數組切片),數組是值類型,而slice爲引用類型,值類型做爲參數傳入函數,只是拷貝了個副本,修改並不會做用到傳入的那個參數,因此通常使用slice做爲參數,免去了拷貝的消耗,可是有坑在裏面,下面寫例子說明。數組
1.slice做爲參數app
package main import "fmt" type DbItem struct { Id int16 Cnt int32 } func combineItem(itemList []DbItem, id int16, cnt int32) { item := DbItem{Id: int16(id), Cnt: int32(cnt)} itemList[0] = item fmt.Printf("combineItem itemList values: %v \n", itemList) } func main() { itemList := make([]DbItem, 5) combineItem(itemList, int16(1), int32(2)) fmt.Printf("main itemList values: %v \n", itemList) }
運行結果以下:
combineItem itemList values: [{1 2} {0 0} {0 0} {0 0} {0 0}]
main itemList values: [{1 2} {0 0} {0 0} {0 0} {0 0}] 函數
2.數組做爲參數。code
package main import "fmt" type DbItem struct { Id int16 Cnt int32 } func combineItem(itemList [5]DbItem, id int16, cnt int32) { item := DbItem{Id: int16(id), Cnt: int32(cnt)} itemList[1] = item fmt.Printf("combineItem itemList values: %v \n", itemList) } func main() { itemList := [5]DbItem{{Id: 3, Cnt: 4}} combineItem(itemList, int16(1), int32(2)) fmt.Printf("main itemList values: %v \n", itemList) }
運行結果以下:
combineItem itemList values: [{3 4} {1 2} {0 0} {0 0} {0 0}]
main itemList values: [{3 4} {0 0} {0 0} {0 0} {0 0}] get
3.特別要注意,若是函數內使用了append,千萬不要把參數當引用來用,會出問題。it
package main import "fmt" type DbItem struct { Id int16 Cnt int32 } func combineItem(itemList []DbItem, id int16, cnt int32) { item := DbItem{Id: int16(id), Cnt: int32(cnt)} itemList = append(itemList, item) fmt.Printf("combineItem itemList values: %v \n", itemList) } func main() { itemList := make([]DbItem, 5) combineItem(itemList, int16(1), int32(2)) fmt.Printf("main itemList values: %v \n", itemList) }
運行結果以下:
combineItem itemList values: [{0 0} {0 0} {0 0} {0 0} {0 0} {1 2}]
main itemList values: [{0 0} {0 0} {0 0} {0 0} {0 0}] import
具體緣由參見:https://segmentfault.com/a/11...List