【发布时间】:2017-10-18 03:49:01
【问题描述】:
我的目的是从特定切片中删除一个元素,代码如下:
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
据我所知,切片会作为引用类型传递给函数调用,为什么不能修改它?
【问题讨论】:
-
切片不是引用类型,实际上不是。
-
另外,可能重复:Golang append an item to a slice。
-
切片不是引用类型,尽管it does use a pointer (or something functionally equivalent) to avoid wasting memory。这意味着内存在两个切片之间共享,但长度甚至上限可能不同。它们本质上是两个不同的项目。您可以在 Go 博客条目“Go Slices: usage and internals”中阅读有关切片的更多信息,尤其是this section。