Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize struct fields

Tags:

go

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

type MyType struct {
    Field string = "default" 
} 
like image 672
Dmitry Avatar asked May 24 '15 21:05

Dmitry


People also ask

Are struct fields initialized?

Struct fields are by default initialized to whatever the Initializer for the field is, and if none is supplied, to the default initializer for the field's type. The default initializers are evaluated at compile time. The default initializers may not contain references to mutable data.

How do you initialize a struct variable?

Initialize structure using dot operator In C, we initialize or access a structure variable either through dot . or arrow -> operator. This is the most easiest way to initialize or access a structure.

Can you initialize values in a struct?

Structure members cannot be initialized with declaration.

How do you initialize a structure object?

Structure members can be initialized using curly braces '{}'.


2 Answers

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.

like image 111
OneOfOne Avatar answered Oct 23 '22 17:10

OneOfOne


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.

like image 42
Stephan Dollberg Avatar answered Oct 23 '22 16:10

Stephan Dollberg