Dmitro
Dmitro

Reputation: 1960

How to initialize struct fields

How can to initialize any fields in golang types? For example:

type MyType struct {
    Field string = "default" 
} 

Upvotes: 10

Views: 9003

Answers (2)

OneOfOne
OneOfOne

Reputation: 99224

You can't have "default" values like that, you can either create a default "constructor" function that will return the defaults or simply assume that an empty / zero value is the "default".

type MyType struct {
    Field string
} 

func New(fld string) *MyType {
    return &MyType{Field: fld}
}

func Default() *MyType {
    return &MyType{Field: "default"}
}

Also I highly recommend going through Effective Go.

Upvotes: 10

Stephan Dollberg
Stephan Dollberg

Reputation: 34538

There is no way to do that directly. The common pattern is to provide a New method that initializes your fields:

func NewMyType() *MyType {
    myType := &MyType{}
    myType.Field = "default"
    return myType

    // If no special logic is needed
    // return &myType{"default"}
}

Alternatively, you can return a non-pointer type. Finally, if you can work it out you should make the zero values of your struct sensible defaults so that no special constructor is needed.

Upvotes: 3

Related Questions