go语言中数组作为参数,在另外函数修改数组的值,为什么会影响到原数组?


package main

import "fmt"

func main() {
    var array = []int{1, 3, 5, 0, 1, 4, 6}
    slices := make([]int, 0)
    slices = append(slices, 1)
    slices = append(slices, 3)
    slices = append(slices, 5)
    slices = append(slices, 0)
    slices = append(slices, 1)
    slices = append(slices, 4)
    slices = append(slices, 6)

    printTes(array)
    printTes(slices)

    fmt.Println("------")
    fmt.Println("main:", array)
    fmt.Println("main:", slices)
}

func printTes(arr []int) {

    arr[4] = 100

    fmt.Println("Tes:", arr)

}

img

在学习过程中遇到这个问题,数组的传值方式是拷贝传值,那为什么在函数中修改了数组的值会影响main函数中数组的值?求解答

数组作为方法参数时,实参和形参指向同一个地址,方法中对改变数组内容,间接影响了原数组内容。