How to initialize struct fields

时间:2015-05-24 21:32:54

标签: go

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

type MyType struct {
    Field string = "default" 
} 

2 个答案:

答案 0 :(得分:6)

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.

答案 1 :(得分:2)

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.