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?
Golang is not OOP language in its official documents. All fields of Golang struct has a determined value(not like c/c++), so constructor function is not so necessary as cpp. If you need assign some fields some special values, use factory functions. Golang's community suggest New.. pattern names.
If you want to emulate
___.new()
syntax you can do something along the lines of:Granted, it is a shame that
Thing.new()
cannot be implemented withoutCThing.new()
also being implemented (iirc) which is a bit of a shame...In Go, a constructor can be implemented using a function that returns a pointer to a modified structure.
For weak dependencies and better abstraction, the constructor does not return a pointer to a structure, but an interface that this structure implements. This design makes it easy to use mock when testing your code.
I like the explanation from this blog post:
log.go
bufio.go
crypto.go