what the differences between &struct vs struct

type test_struct struct {
    Message string
}

func (t *test_struct) SayP() {
    fmt.Println(t.Message)
}

func (t *test_struct) UpdateP(m string) {
    t.Message = m
}

func main() {
    ts := &test_struct{}
    ts.Message = "test"
    ts.SayP()
    ts.UpdateP("test2")
    ts.SayP()

    tsp := test_struct{}
    tsp.Message = "test"
    tsp.SayP()
    tsp.UpdateP("test2")
    tsp.SayP()
}

why they work the same, what the difference between &test_struct{} and test_struct{} ?

tsp := test_struct{}

should not work well

>Solution :

The methods are defined for *test_struct. That means, if the instance of test_struct is addressable, you can still call the methods on it. In you example, both ts and tsp are addressable, so when you call tsp.SayP, the address of tsp is passed as the receiver.

In the following situation, the test_struct instance will not be addressable:

v:=map[string]test_struct{
  "a": test_struct{},
}
v["a"].SayP() // This will not work

Above, v["a"] is not addressable, because it is a copy of the value stored in the map. Thus, you cannot call SayP(). If you declare:

v:=map[string]*test_struct{
  "a": &test_struct{},
}
v["a"].SayP() // This will  work

then it will work, because v["a"] is addressable.

Leave a Reply