patterngoCritical
Constructors in Go
Viewed 0 times
constructorsstackoverflowprogramming
Problem
I have a struct and I would like it to be initialised with some sensible default values.
Typically, the thing to do here is to use a constructor but since go isn't really OOP in the traditional sense these aren't true objects and it has no constructors.
I have noticed the init method but that is at the package level. Is there something else similar that can be used at the struct level?
If not what is the accepted best practice for this type of thing in Go?
Typically, the thing to do here is to use a constructor but since go isn't really OOP in the traditional sense these aren't true objects and it has no constructors.
I have noticed the init method but that is at the package level. Is there something else similar that can be used at the struct level?
If not what is the accepted best practice for this type of thing in Go?
Solution
There are actually two accepted best practices:
Document if a zero value of your type is usable or not (in which case it has to be set up by one of the
- Make the zero value of your struct a sensible default. (While this looks strange to most people coming from "traditional" oop it often works and is really convenient).
- Provide a function
func New() YourTypor if you have several such types in your package functionsfunc NewYourType1() YourType1and so on.
Document if a zero value of your type is usable or not (in which case it has to be set up by one of the
New... functions. (For the "traditionalist" oops: Someone who does not read the documentation won't be able to use your types properly, even if he cannot create objects in undefined states.)Context
Stack Overflow Q#18125625, score: 182
Revisions (0)
No revisions yet.