通过传递指针来修改切片

huangapple go评论79阅读模式
英文:

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)
}

Playground链接

英文:

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?

Playground link:

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:]
}

<kbd>playground</kbd>

huangapple
  • 本文由 发表于 2014年9月18日 07:55:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/25902155.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定