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
- Performance - which one is better & why?
- Garbage Collection - which one is better & why?
- Any Memory effects?
- Any other effects!
Which one should be used on above example and why?
Please put your answer only based on above example, which method would you have choosed above and why?
Thanks