This question already has an answer here:
I'm trying to learn Go. I learned that structs and arrays are copied by value (when passing them to functions or assigning them to variables). So we use pointers to allow modifying them and to save memory.
The thing is, in some situations I always find them use pointers to structs.
For instance, in an official web application tutorial they used the code
func (p *Page) save() error {
filename := p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}
Here it no data change occurs to the struct. This happens in may other places in official packages and 3rd party ones.
Another case is when they return a &struct{}. An example from the same link above:
func loadPage(title string) *Page {
filename := title + ".txt"
body, _ := ioutil.ReadFile(filename)
return &Page{Title: title, Body: body}
}
So, in which cases and places the pointer should be used?
</div>
This is one think cool about go, that we can use pointer to save memory usage.
from my case I use pointers whenever I get the data from database and wanted to change something from it. therefor I use pointer to save memory usage.
example :
func GetUserShopInfo(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
//....
shop_data, err := shop.GetUserShopInfo(user_id)
// manipulate shop_data
shop.ChangeValue(&shop_data)
// you will get the result here without creating new variable
}
And then I use pointer whenever I want to share the value, and changing them without having to create new variable to get the result.
example :
func main(){
a := 10
ChangeValue(&a)
// a will change here
}
func ChangeValue(a *int){
// do something to a
}
the same thing about struct. I used pointer so that I can pass and modify value in variable
example :
type Student struct {
Human
Schoool string
Loan float32
}
// use pointer so that we can modify the Loan value from previous
func (s *Student) BorrowMoney(amount float32) {
s.Loan += amount
}
In conclusion I used pointer in every cases whenever I feel like to share the value.