Changing a slice by passing its pointer

假装没事ソ 提交于 2019-12-11 11:14:19

问题


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:


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

playground



来源:https://stackoverflow.com/questions/25902155/changing-a-slice-by-passing-its-pointer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!