How to set default values for struct fields in Go?
Hello everyone! I'm new to Go and ran into a problem: Go doesn't have constructors and doesn't have a built-in mechanism for specifying default values for struct fields, like in Python or PHP. Let's say I have a struct for an application configuration:
```go
type Config struct {
Port int
Timeout int
Debug bool
}
```
I want `Port` to default to 8080, `Timeout` to 30 seconds, and `Debug` to `false`. But when I create a struct `cfg := Config{}`, all fields get zero values (0, 0, false). I have to explicitly specify all fields every time: `cfg := Config{Port: 8080, Timeout: 30}`. This is inconvenient, especially if the struct has many fields and I want some of them to have reasonable default values.
I tried using struct tags, but they
No answers yet.
Log in to leave an answer