Home >Backend Development >Golang >How to Set Default Values in Go Structs?

How to Set Default Values in Go Structs?

DDD
DDDOriginal
2024-12-23 17:13:101010browse

How to Set Default Values in Go Structs?

How to Initialize 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:

Using a Constructor Function

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn