为什么它无法通过函数调用修改切片的长度或容量?

pir*_*san -1 function go slice

我的目的是从特定切片中删除一个元素,代码如下:

func main() {
    s := []int{0, 1, 2, 3, 4}
    remove(s, 3)
    fmt.Println(s, len(s), cap(s))
}

func remove(s []int, idx int) {
    if idx < 0 || idx >= len(s) {
        return
    }
    copy(s[idx:], s[idx+1:])
    s = s[:len(s)-1]
    fmt.Println(s, len(s), cap(s))
}
Run Code Online (Sandbox Code Playgroud)

但输出显示:

[0 1 2 4] 4 5 [0 1 2 4 4] 5 5

据我所知,slice将作为引用类型传递给函数调用,为什么它不能修改它?

Aka*_*all 5

Slice有三个值:

1)指向底层数组的指针

2)长度

3)容量

将切片传递给函数时,您将传递所有这三个值的副本.因此,您无法更改长度和容量,但由于您具有指向基础数组的指针,因此您可以更改数组内的值.