I have read some of the stack overflow question related to "why pointer and why not pointer", but I could not understand much.
So, I thought to understand and learn based on my situation on golang
perspective.
I have 2 struct
type Discussion struct {
ID string `json:"id"`
Title string `json:"title"`
Content string `json:"content"`
Owner *User `json:"owner"`
}
type User struct {
ID string `json:"id"`
Name string `json:"name"`
}
In above Discussion
struct you can see, I used *User
for Owner
field.
Considering situation, I do not have to change data for Owner
after creating value for Discussion
like below, should I use only User
or it's better to use *User
like below
func main() {
u := User {
ID: "2",
Name: "StackOverflow",
}
d := Discussion{
ID: "1",
Title: "This is my family",
Content: "I love my family",
Owner: &u,
}
}
or, Should I use like below -
type Discussion struct {
ID string `json:"id"`
Title string `json:"title"`
Content string `json:"content"`
Owner User `json:"owner"`
}
type User struct {
ID string `json:"id"`
Name string `json:"name"`
}
func main() {
u := User {
ID: "2",
Name: "StackOverflow",
}
d := Discussion{
ID: "1",
Title: "This is my family",
Content: "I love my family",
Owner: u,
}
}
I have following question based on above 2 situation
Which one should be used on above example and why?
Thanks
Performance wise, it's better to use pointers as everything with golang is pass by value. So instead of golang having to look up the values of the User struct to then pass to the Discussion struct, it only passes the pointer to it. This also applies to how attaching methods to struct works. func (u *User)Example{} will execute faster as only the pointer has to be passed in. I think performance is negligible however
No Clue, I've only read one post about garbage collection issues by twitch and they said they where all resolved by golang 1.7. There are very few situations where you are worried about this.
If you don't use a pointer to User, updates to the User struct won't reflect inside of the Discussion struct. See this example here. Notice even though User's ID has been updated, it's not reflected in Discussion.
/shrug