dqrb4228 2017-03-09 22:32
浏览 114
已采纳

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

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条回答 默认 最新

  • donoworuq450547191 2017-03-09 22:34
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?