Home >Backend Development >Golang >How Do I Initialize Structs in Go Without Constructors?

How Do I Initialize Structs in Go Without Constructors?

Susan Sarandon
Susan SarandonOriginal
2024-12-18 02:47:14186browse

How Do I Initialize Structs in Go Without Constructors?

Constructors in Go

When dealing with custom types defined as structs in Go, it may be desirable to initialize them with sensible default values upon creation. However, unlike traditional object-oriented programming languages, Go does not have dedicated constructors for structs.

Alternative to Constructors: New Functions

To address this situation, Go engineers commonly employ "New" functions. These functions accept necessary parameters for initialization and return a pointer to a new struct instance:

type Thing struct {
    Name  string
    Num   int
}

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

This approach allows for the initialization of struct values with specific defaults, such as assigning a value to the "Num" field.

Condensed New Function Syntax

For simple structs, a condensed syntax can be used:

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

Non-Pointer Return Types

If returning a pointer is not desired, a "make" function can be used instead of "New":

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

The above is the detailed content of How Do I Initialize Structs in Go Without 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