1

Usually when I see a field declared on a struct it's without a pointer or a dereferenced pointer symbol *, however in several code snippets where I've seen a database field in a struct it's with a pointer dereference as you see below. Why is that necessary?

type DB struct {
    *bolt.DB
}
func Open(path string, mode os.FileMode) (*DB, error) {
    db, err := bolt.Open(path, mode)
    if err != nil {
        return nil, err
    }
    return &DB{db}, nil
}
Leahcim
  • 40,649
  • 59
  • 195
  • 334

1 Answers1

2

or a dereferenced pointer symbol *

That is the norm, for complex non-value type, in order to avoid making a copy.
See Golang book "Pointers" for example of struct with pointer(s) in them.

return &DB{db}

That returns a pointer to the newly created DB instance.
As noted in "Can you “pin” an object in memory with Go?":

Note that, unlike in C, it's perfectly OK to return the address of a local variable; the storage associated with the variable survives after the function returns

From "Pointer/Value Subtleties":

Go is also pass by value, but it has both pointers and value types. Pointers refer to a certain memory location, and allow you to mutate the data at that location


For more, see "Best practice “returning” structs in Go?"

Use pointers for big structs or structs you'll have to change, and otherwise use values, because getting things changed by surprise via a pointer is confusing.

Community
  • 1
  • 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • thanks, so what makes it a "complex non-value type"? – Leahcim Aug 22 '14 at 17:31
  • @Leahcim this is addressed in http://stackoverflow.com/a/23551970/6309: Small structs like type `Point struct { latitude, longitude float64 }` don't need pointer. Anything bigger than that could need pointer to avoid copy. – VonC Aug 22 '14 at 17:45