How many times have you written a factory function just to initialize a struct with proper default value?
For example:
// PagingOption ...
type PagingOption struct {
    Page int
    Size int
}
We usually want BOTH to have default values. Let's say page=1&size=25, but anywhere we want to use PagingOption we are either 
- Write and use a factory function which properly build a PagingOption
- Write and use an Initfunction which properly build aPagingOption
- Instantiate using object literal and fill it with default value
- Validate PagingOptionin every consumer and fallback to default value if necessary
- Option 1forces all developer to remember not to usenew(PagingOption)orPagingOption{}.
- Option 2forces all developer to remember calling.Initafter initializingPagingOption
- Options 3forces all developer to know what is the agreed default values.
- Options 4forces all developer to remember checking default value before using thePagingOption
All options contribute to human error which can be mitigated just by having a proper constructor.
 

 
    
Top comments (1)
You can always use the functional options pattern to assign default values...
dave.cheney.net/2014/10/17/functio...