Home >Backend Development >Golang >How Can I Initialize Go Structs Without Traditional Constructors?

How Can I Initialize Go Structs Without Traditional Constructors?

Susan Sarandon
Susan SarandonOriginal
2024-12-24 05:29:18202browse

How Can I Initialize Go Structs Without Traditional Constructors?

Can Constructors Be Used to Initialize Go Structs?

In Go, structs can be initialized with sensible default values through various methods. Despite the lack of traditional constructors due to Go's non-OOP nature, there are alternative techniques to achieve similar functionality.

Method 1: NewThing Function with Pointer Return

When zero values are unsuitable, one option is to create a "NewThing" function that returns a pointer to a newly initialized struct:

type Thing struct {
    Name  string
    Num   int
}

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

Method 2: Condensed "NewThing" Function

For simpler structs, a more concise method is available:

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

Method 3: "makeThing" Function with Value Return

If returning a pointer is not desired, the function can be named "makeThing" and return a value:

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

Reference

For further details, refer to the "Allocation with new" section in Effective Go.

The above is the detailed content of How Can I Initialize Go Structs Without Traditional Constructors?. 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