通过传递指针来修改切片

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

Changing a slice by passing its pointer

问题

我有一个切片,我想使用一个函数来改变它(例如,我想删除第一个元素)。我想使用指针,但是我仍然无法对其进行索引。我做错了什么?

  1. func change(list *[]int) {
  2. fmt.Println(*list)
  3. *list = *list[1:] //这一行搞砸了一切
  4. }
  5. var list = []int{1, 2, 3}
  6. func main() {
  7. change(&list)
  8. }

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:

  1. func change(list *[]int) {
  2. fmt.Println(*list)
  3. *list = *list[1:] //This line screws everything up
  4. }
  5. var list = []int{1, 2, 3}
  6. func main() {
  7. change(&list)
  8. }

答案1

得分: 3

你需要使用(*list)

  1. func change(list *[]int) {
  2. *list = (*list)[1:]
  3. }

或者使用另一种通常更符合Go语言习惯的方法:

  1. func change(list []int) []int {
  2. return list[1:]
  3. }

[kbd]playground/kbd

英文:

You need to use (*list).

  1. func change(list *[]int) {
  2. *list = (*list)[1:]
  3. }

or a different approach that's usually more go idomatic:

  1. func change(list []int) []int {
  2. return list[1:]
  3. }

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

确定