function - 为什么不能通过函数调用修改 slice 的长度或容量?

标签 function go slice

我的目的是从特定的 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))
}

但输出显示:

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

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

最佳答案

Slice 包含三个值:

1) 指向底层数组的指针

2)长度

3)容量

当您将 slice 传递给函数时,您传递的是所有这三个值的副本。因此,您无法更改长度和容量,但由于您拥有指向底层数组的指针,您可以更改数组内的值。

关于function - 为什么不能通过函数调用修改 slice 的长度或容量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46802489/

相关文章:

python - 在 [ :index] 上使用动态索引列出切片

javascript - 对事件函数中 if/else 的使用进行故障排除

javascript - 格式化javascript函数的正确方法

function - 在函数中使用 EXECUTE 时出现 PostgreSQL 语法错误

javascript - 如何在 Golang 中使用 JQuery 数据表?

pointers - 戈朗 : Why selector to pointers is illegal after comparison?

python - 按下按钮时调用函数-pyqt

go - 为什么会有这样的结果?

arrays - 不能使用 "a"(字符串类型)作为 go 中数组元素的类型

string - ResponseWriter.Write 和 io.WriteString 有什么区别?