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

How Do I Initialize Structs in Go Without Constructors?

Susan Sarandon
Release: 2024-12-18 02:47:14
Original
254 people have browsed it

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

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

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

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 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template