Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading