go-修改切片的指针不会修改原始的

I try to create a struct where one field is a pointer to the existing empty slice. Then I modify struct's field, and later I try to get the new content from the original slice - but it's still empty!

Here is the demo code:

package main

import (
    "fmt"
)

type A struct {
    B []int
}

func main() {
    c := []int{}

    a := &A{
        B: c,
    }

    a.B = append(a.B, 5)

    fmt.Println(c)
    fmt.Println(a)
}

The result here is:

[]
&{[5]}

The question is - how do I get the actual slice content from both original slice and struct's field? I have no passing the slice to the function as a param here.

You can use a slice of pointers like in example below:

package main

import (
    "fmt"
)

type A struct {
    B *[]int
}

func main() {
    c := []int{}

    a := &A{
        B: &c,
    }

    *a.B = append(*a.B, 4)
    *a.B = append(*a.B, 5)

    fmt.Println(c)

    fmt.Println(a.B)
}

Result The result is