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

How to Set Default Values in Go Structs?

DDD
Release: 2024-12-23 17:13:10
Original
969 people have browsed it

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
}
Copy after login

Example Usage:

// create a Something struct
something := NewSomething("Example Text")

// access the DefaultText field
fmt.Println(something.DefaultText) // Output: default text
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template