英文:
Changing a slice by passing its pointer
问题
我有一个切片,我想使用一个函数来改变它(例如,我想删除第一个元素)。我想使用指针,但是我仍然无法对其进行索引。我做错了什么?
func change(list *[]int) {
fmt.Println(*list)
*list = *list[1:] //这一行搞砸了一切
}
var list = []int{1, 2, 3}
func main() {
change(&list)
}
英文:
I have a slice that I want to change (for example i want to remove the first element) using a function. I thought to use a pointer, but I still can't index it. What am I doing wrong?
func change(list *[]int) {
fmt.Println(*list)
*list = *list[1:] //This line screws everything up
}
var list = []int{1, 2, 3}
func main() {
change(&list)
}
答案1
得分: 3
你需要使用(*list)
。
func change(list *[]int) {
*list = (*list)[1:]
}
或者使用另一种通常更符合Go语言习惯的方法:
func change(list []int) []int {
return list[1:]
}
[kbd]playground/kbd
英文:
You need to use (*list)
.
func change(list *[]int) {
*list = (*list)[1:]
}
or a different approach that's usually more go idomatic:
func change(list []int) []int {
return list[1:]
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论