Hi,
I am not an experienced programmer and I am newbie to Go. I was trying to interiorize the pointer concept. To do so I made the following test:
package main
import (
"fmt"
"xpckg"
)
func main() {
s := new(xpckg.MyType)
fmt.Println("&s in main:", &s, "\ns in main:", s,"\n*s in main:", *s, "\ns.Test in main:", s.Test, "\n&s.Test in main:", &s.Test, "\n")
s.Callxpckg()
s.Field1 = 2
s.Test = "In main"
fmt.Println("&s in main:", &s, "\ns in main:", s,"\n*s in main:", *s, "\ns.Test in main:", s.Test, "\n&s.Test in main:", &s.Test, "\n")
}
package xpckg
import (
"fmt"
)
type MyType struct {
Field1 int
Test string
}
func (s *MyType) Callxpckg() {
s.setFields()
fmt.Println("&s in Callxpckg:", &s, "\ns in Callxpckg:", s, "\n*s in Callxpckg:", *s, "\ns.Test in Callxpckg:", s.Test, "\n&s.Test in Callxpckg:", &s.Test, "\n")
}
func (s *MyType) setFields() {
s.Field1 = 1
s.Test = "Inside pckg"
fmt.Println("&s in setFields:", &s,"\ns in setFields:", s, "\n*s in setFields:", *s, "\ns.Test in setFields:", s.Test, "\n&s.Test in setFields:", &s.Test, "\n")
}
And received the following answer:
&s in main: 0xc042052018
s in main: &{0 }
*s in main: {0 }
s.Test in main:
&s.Test in main: 0xc042040408
&s in setFields: 0xc042052030
s in setFields: &{1 Inside pckg}
*s in setFields: {1 Inside pckg}
s.Test in setFields: Inside pckg
&s.Test in setFields: 0xc042040408
&s in Callxpckg: 0xc042052028
s in Callxpckg: &{1 Inside pckg}
*s in Callxpckg: {1 Inside pckg}
s.Test in Callxpckg: Inside pckg
&s.Test in Callxpckg: 0xc042040408
&s in main: 0xc042052018
s in main: &{2 In main}
*s in main: {2 In main}
s.Test in main: In main
&s.Test in main: 0xc042040408
I was expecting that the address stored in pointer to myType (s) would be the same, however I could not check this given that cmd retrieves &{0 }, is there a reason for this?
I understand why the address of the variables s (&s) that store the address to myType are different.
However I cannot understand why s.Test have the same address (&s.Test) in all places given that &s does not have the same address in all functions? For the same reason as &s stores different values shouldn’t this store different values too? On the other end I didn’t defined Test as a pointer to a string rather I defined it as string so it also make sense that &s.Test retrieves the address of the variable and not the address of the address.
I am a bit puzzled? Can somebody provide help understanding this? Either by value or by reference.
Thank you.