How to create a configuration struct with default values using embedding in Go?

To create a configuration struct with default values using embedding in Go, follow these steps:

  1. Start by creating a struct for the default configuration, let's say DefaultConfig. Add the default values as fields in this struct.
type DefaultConfig struct { Name string Age int IsMale bool Language string }
  1. Now, create your configuration struct that embeds the DefaultConfig struct. Let's call it Config.
type Config struct { DefaultConfig // Embedding DefaultConfig struct CustomField string }
  1. To create an instance of 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{}
  1. You can then access the default values as well as add or modify values specific to 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: ""
  1. Finally, if you want to override any of the default values, you can do so by explicitly assigning new values to the corresponding fields.
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.