go切片和map传参注意事项

切片传参

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]

传参到函数里面,如果重新赋值,会直接在主程序中表现出来,但是如果是扩容新加的数据,只会在函数中生效,不会在主程序中生效,说明传参的时候slice是值传递,但是每个指向内容是引用类型

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]

传参到函数里面,不管是改变值还是新加值,函数和主程序都会表现出来,说明map虽然值传递,但是最终指向都是引用类型

你可能感兴趣的:(go切片和map传参注意事项)