This is a creation in Article, where the information may have evolved or changed.
Recent projects have encountered similar problems, make a record.
For example, [5]int is an array, []int is a slice (array slice), the arrays are value types, and slice is a reference type, the value type is passed as a parameter to the function, only a copy is copied, the modification does not affect the passed parameter, so the general use of slice as a parameter, The consumption of the copy is eliminated, but there is a pit in it, below is an example to illustrate.
1.slice as a parameter
package mainimport "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)}
The results of the operation are as follows:
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. Array as a parameter.
package mainimport "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)}
The results of the operation are as follows:
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}]
3. In particular, it is important to note that if append is used within a function, you should never use parameters as references.
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) }
The results of the operation are as follows:
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}]
For specific reasons see: Https://segmentfault.com/a/11 ...