To create a configuration struct with default values using embedding in Go, follow these steps:
DefaultConfig
. Add the default values as fields in this struct.type DefaultConfig struct {
Name string
Age int
IsMale bool
Language string
}
DefaultConfig
struct. Let's call it Config
.type Config struct {
DefaultConfig // Embedding DefaultConfig struct
CustomField string
}
Config
with default values, you can simply create a variable of type Config
. Since Config
embeds DefaultConfig
, it will inherit the default values defined in DefaultConfig
.cfg := Config{}
Config
.fmt.Println(cfg.Name) // Default value: ""
fmt.Println(cfg.Age) // Default value: 0
fmt.Println(cfg.IsMale) // Default value: false
fmt.Println(cfg.Language) // Default value: ""
fmt.Println(cfg.CustomField) // Default value: ""
cfg.Name = "John"
cfg.Age = 30
cfg.CustomField = "Some value"
By using embedding, the Config
struct inherits the default values defined in the DefaultConfig
struct, and you can easily override or add more values specific to the Config
struct.