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

How Can I Set Default Values in Go Structs?

Susan Sarandon
Susan SarandonOriginal
2024-12-25 08:41:09873browse

How Can I Set Default Values in Go Structs?

Setting Default Values in Go Structs

This question explores various techniques for setting default values in Go structs. The issue stems from the fact that Go structs do not support default values natively.

One possible solution involves creating a separate constructor function. For example, consider the following struct:

type Something struct {
    Text string
    DefaultText string
}

We can then define a constructor function to create new instances of the struct with desired default values:

func NewSomething(text string) Something {
   something := Something{}
   something.Text = text
   something.DefaultText = "default text"
   return something
}

By calling NewSomething with the desired text, we can create an instance with appropriate default values for DefaultText. This approach offers flexibility in setting default values based on the constructor function's arguments, allowing for more complex scenarios.

The above is the detailed content of How Can I 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