Home >Backend Development >Golang >How to Set Default Values in Go Structs?
When working with Go structs, you may encounter the need to set default values for certain fields. There are various techniques available to achieve this:
One method involves writing a separate constructor function to instantiate the struct and initialize the fields with default values. For instance:
//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 }
Example Usage:
// create a Something struct something := NewSomething("Example Text") // access the DefaultText field fmt.Println(something.DefaultText) // Output: default text
The above is the detailed content of How to Set Default Values in Go Structs?. For more information, please follow other related articles on the PHP Chinese website!