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