Linus
Linus

Reputation: 4783

When to store pointers to structs in variables instead of the struct itself

I'm currently learning Go and am following a tutorial about how to use Go with Stripe. There is this example code:

package main

import (
  "fmt"
  "github.com/stripe/stripe-go"
  "github.com/stripe-go/customer"
)

func main() {
  sc := &client.API{}
  sc.Init("somekey")
  c, _ := sc.Customers.Get("customerid", nil)
  // ...
}

What is/could be the reason that sc stores the pointer to the struct and not the struct itself?

Upvotes: 1

Views: 671

Answers (1)

Eli Bendersky
Eli Bendersky

Reputation: 273796

[To supplement the comment you received]

While in this case with the small code sample it's hard to say, in most scenarios you'll see non-trivial types passed around by pointer to enable modification. As an anti-example, consider this code which uses a variable of a struct type by value:

type S struct {
    ID int
}

func (s S) UpdateID(i int) {
    s.ID = i
}

func main() {
    s := S{}
    s.UpdateID(99)

    fmt.Println(s.ID)
}

What do you think this will print? It will print 0, because methods with value receivers cannot modify the underlying type.

There's much information about this in Go - read about pointers, and about how methods should be written. This is a good reference: https://golang.org/doc/faq#methods_on_values_or_pointers, and also https://golang.org/doc/effective_go#pointers_vs_values

Back to your example: typically non-trivial types such as those representing a "client" for some services will be using pointers because method calls on such types should be able to modify the types themselves.

Upvotes: 2

Related Questions