简体   繁体   中英

How to get slice item using pointer to that slice

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
PS
Sorry for asking this kind of primitive question. I'm new in go

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM