Home >Backend Development >Golang >How Can I Initialize Structs with Sensible Default Values in Go?

How Can I Initialize Structs with Sensible Default Values in Go?

Susan Sarandon
Susan SarandonOriginal
2024-12-26 15:04:09517browse

How Can I Initialize Structs with Sensible Default Values in Go?

Constructors in Go: A Guide to Sensible Default Values

When working with structs in Go, initializing them with sensible default values can be crucial for ensuring their proper functioning. While Go lacks traditional constructors, there are several methods that can be employed to achieve this objective.

Init Method

The init method, although defined at the package level, can be utilized to perform initialization tasks for structs within the package. However, it isn't directly tied to the struct and is not invoked upon struct creation.

New Functions

A common practice in Go is to define New functions that return initialized pointers to structs. These functions allow for the assignment of default values during struct initialization:

func NewThing(someParameter string) *Thing {
    p := new(Thing)
    p.Name = someParameter
    p.Num = 33 // Sensible default value
    return p
}

Condensed New Functions

For simple structs, a condensed version of the New function can be used, directly returning an initialized struct:

func NewThing(someParameter string) *Thing {
    return &Thing{someParameter, 33}
}

Make Functions

Make functions are similar to New functions but return structs by value rather than pointers. This is useful when you don't require a pointer to the struct:

func makeThing(name string) Thing {
    return Thing{name, 33}
}

Reference

For further information on allocation using new, refer to the effective Go documentation: https://go.dev/doc/effective_go#allocation

The above is the detailed content of How Can I Initialize Structs with Sensible Default Values in Go?. 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