1

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?

HorusCoding
  • 675
  • 1
  • 6
  • 13
  • Also related / possible duplicate of [Why should constructor of Go return address?](http://stackoverflow.com/questions/31932822/why-should-constructor-of-go-return-address/31934189#31934189) – icza Jan 08 '17 at 11:17

1 Answers1

0

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.

Gujarat Santana
  • 9,854
  • 17
  • 53
  • 75
  • 1
    Passing around pointers make them escape to the heap. For small structs that can be inexpensively passed around (pass by value) in the stack, this could over time build unnecessary GC pressure. It's always a tradeoff. – Nadh Jan 08 '17 at 11:20