goconstructorpass-by-value

returning value vs pointer in Go constructor


When building a simple object in go, what's the difference between these alternatives?

func NewGender(value string) Gender {
    return Gender{strings.TrimSpace(value)}
}

func NewGender(value string) *Gender {
    return &Gender{strings.TrimSpace(value)}
}

Solution

  • The question is a really broad one, and it depends heavily on the rest of your API. So here are just some things you might need to consider when choosing one over another (in no particular order):