如何使用指向切片的指针获取切片项

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

How to get slice item using pointer to that slice

问题

有一个整数切片和一个接受指向切片的指针作为参数的函数。

mainSlice := []int{0,8,5,4,6,9,7,1,2,3,6,4,5,7}
doSmthWithSlice(&mainSlice)

有没有办法使用指向切片的指针获取切片项,但不将指针指向的值复制到新的切片中?

func doSmthWithSlice(slcPtr *[]int) {
    (*slcPtr)[3] = 777 // 这样是不行的,因为*[]int不支持索引

    // 不想这样实现
    newSlice := *slcPtr
    newSlice[3] = 777
    *slcPtr = newSlice
}

谢谢
附言
对于提出这种原始问题我感到抱歉。我是Go语言的新手

英文:

Have a slice of ints and a function that accepts a pointer to a slice as a parameter.

mainSlice := []int{0,8,5,4,6,9,7,1,2,3,6,4,5,7}
doSmthWithSlice(mainSlice)

Is there any ways to get the slice item using the pointer to the slice, but without copying the value that the pointer points into new slice?

func doSmthWithSlice(slcPtr *[]int) {
    *slcPtr[3] = 777 // this does NOT works, because *[]int does not support indexing

    // Don't want to implement it 
    // like this
    newSlice := *slcPtr
    newSlice[3] = 777
    *slcPtr = newSlice
}

Thank you
P.S.
Sorry for asking this kind of primitive question. I'm new in go

答案1

得分: 2

运算的顺序很重要:你需要先解引用指针,然后再对其进行索引。

func doSmthWithSlice(slPtr *[]int) {
    (*slcPtr)[3] = 777 
}

如果没有括号,索引操作符会应用于切片指针,这是一个无效的操作。

英文:

The order of operations matter: you need to first dereference the pointer, and then index it.

func doSmthWithSlice(slPtr *[]int) {
    (*slcPtr)[3] = 777 
}

Without the parentheses, the index operator is applies to the slice pointer; an invalid operation.

huangapple
  • 本文由 发表于 2017年3月10日 06:32:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/42706786.html
匿名

发表评论

匿名网友

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

确定