SoFunction
Updated on 2025-03-05

Specific use of []*int and *[]int in go language

[]*int is a slice pointing to a pointer, which is essentially a slice, but the elements stored in the slice are pointers;
*[]int is a pointer to a slice, essentially a pointer, and you can use * to get the slice;

Simple remembering method: Read from right to left, the last symbol is [], which means it is a slice, and the penultimate symbol is * means a pointer in the slice; read from right to left, the last symbol is *, which means it is a pointer, and the penultimate symbol is [] means the pointer points to a slice type.

For []*int, you can use for _, ptr := range slice to obtain the pointer in the slice, and use *ptr to obtain the corresponding value of the element (essentially a pointer/address).
For *[]int, you can use *slice to get the entire slice.

[]*int

func main() {
    var a = 1
    var b = 2
    var slice []*int
    slice = append(slice, &a)
    slice = append(slice, &b)
    for _, ptr := range slice {
        (*ptr, " ")
    }
}

Output: 1 2

*[]int

func main() {
    var a = 1
    var b = 2
    var slice *[]int
    arr := []int{a, b}
    slice = &arr
    (*slice)
}

Output:[1 2]

This is the introduction to this article about the specific use of []*int and *[]int in go language. For more related content in go languages ​​[]*int and *[]int, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!