How to set default values in Go structs

Prateek picture Prateek · May 10, 2016 · Viewed 177.7k times · Source

There are multiple answers/techniques to the below question:

  1. How to set default values to golang structs?
  2. How to initialize structs in golang

I have a couple of answers but further discussion is required.

Answer

vodolaz095 picture vodolaz095 · May 10, 2016

One possible idea is to write separate constructor function

//Something is the structure we work with
type Something struct {
     Text string 
     DefaultText string 
} 
// NewSomething create new instance of Something
func NewSomething(text string) Something {
   something := Something{}
   something.Text = text
   something.DefaultText = "default text"
   return something
}