0

A lot of examples out there (like this) show something like:

type person struct {
    name string
    age int
}

func NewPerson(n string, a int) *person {
    p := person{n, a}
    return &p
}

Whilst I'm comfortable with the mechanics of the above, there seems to be an idiom of always returning a pointer to the new struct.

Why wouldn't you simply always return the actual struct itself, rather than a pointer to it?

The struct is small, and future mutability doesn't come into it as mentioned in this question. Also, that question doesn't specifically address the constructor idiom. Is it all about perceived efficiency and memory?

  • Please explain to me why this is a duplicate –  Oct 11 '17 at 20:23
  • 1
    @JimB your dupe hammer is friendly challenged. I assume the both of you manage to work this out in an orderly manner? – rene Oct 11 '17 at 20:32
  • 1
    The actual determinant for returning a pointer or not is dependent on the context, and sometimes just personal preference. The _reasons_ you may choose one over the other are clearly laid out in the duplicates. The reasons why you could always return a struct value _in this particular case_ are covered as well. Seeing how there are many cases where you need to use a pointer, the additional question of "why can't I always not use a pointer" doesn't seem to make sense. – JimB Oct 11 '17 at 20:48
  • After reading the answers to the two duplicates, what questions remain? – Jonathan Hall Oct 12 '17 at 07:47

0 Answers0