How can to initialize any fields in golang types? For example:
type MyType struct {
Field string = "default"
}
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.
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.
Structure members cannot be initialized with declaration.
Structure members can be initialized using curly braces '{}'.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With