切片傳參
func TestSliceParam(t *testing.T) {
a := []int{1, 2, 3}
fmt.Println(a)
SliceFunc(a)
fmt.Println(a)
}
func SliceFunc(a []int) {
a[0] = 11
a = append(a, 4)
fmt.Println(a)
}
output:
[1 2 3]
[11 2 3 4]
[11 2 3]
傳參到函數(shù)里面,如果重新賦值,會(huì)直接在主程序中表現(xiàn)出來谱净,但是如果是擴(kuò)容新加的數(shù)據(jù)窑邦,只會(huì)在函數(shù)中生效,不會(huì)在主程序中生效壕探,說明傳參的時(shí)候slice是值傳遞冈钦,但是每個(gè)指向內(nèi)容是引用類型
map傳參
func TestMapParam(t *testing.T) {
a := map[int]int{1: 11, 2: 22, 3: 33}
fmt.Println(a)
MapFunc(a)
fmt.Println(a)
}
func MapFunc(a map[int]int) {
a[1] = 22
a[4] = 44
fmt.Println(a)
}
output:
map[1:11 2:22 3:33]
map[1:22 2:22 3:33 4:44]
map[1:22 2:22 3:33 4:44]
傳參到函數(shù)里面,不管是改變值還是新加值李请,函數(shù)和主程序都會(huì)表現(xiàn)出來瞧筛,說明map雖然值傳遞,但是最終指向都是引用類型