This is a creation in
Article, where the information may have evolved or changed.
First recommend a rain mark of the Great God's new book: "Golang Source Analysis (fifth edition)".
Go to the chase. Golang and other languages do not make sense, he added a slice , this is different from the traditional array, but we use it and also in accordance with the usage of the array, easy to confuse.
First of all, I understand the traditional array, the name of the array is the array in memory of the first address, access to each child element is the first address plus child element length access. So this should be a reference object type.
and Golang slice , citing a rain mark the great God's article explains:
Runtime.h
struct Slice{byte* array;uintgo len;uintgo cap;}
sliceThe bottom layer is implemented by the struct implementation, so the time to pass is the value copy pass, but slice the content is implemented by array pointers. This behavior can occur: * * * Pass by value, len and will cap not change, so the use of the time will not feel the content changes, but actually the byte array is changed.
On the code:
package mainimport "fmt"func main() {testMap := make(map[int64]int64)fmt.Println(testMap)FuckMap(testMap)fmt.Println(testMap)FuckMap2(testMap)fmt.Println(testMap)testSlice := []int64{}fmt.Println(testSlice)FuckSlice(testSlice)fmt.Println(testSlice)FuckSlice2(&testSlice)fmt.Println(testSlice)}func FuckMap(t map[int64]int64) map[int64]int64 {t[1] = 1return t}func FuckMap2(t map[int64]int64) map[int64]int64 {t[1] = 2return t}func FuckSlice(a []int64) []int64 {a = append(a, 1)return a}func FuckSlice2(a *[]int64) *[]int64 {*a = append(*a, 1)return a}
Look directly at the rear half. The modification of a function is ineffective FuckSlice slice because slice it is passed by value, and then we force it to be passed by reference, that is, the slice address passed as a parameter, then the modification is working. Therefore, for slice the modified operation to be aware, it is possible that the modification failed.
Original link: Dog day slice, reproduced please indicate the source!