Junior — Middle
How is default value passing implemented in function parameters in Go?
sobes.tech AI
Answer from AI
The Go language does not have built-in support for default parameter values in functions, as in some other languages (e.g., Python or C++). To implement similar behavior, the following approaches are usually used:
- Function overloading via variadic parameters — pass a variable number of arguments to the function and check their presence inside:
func greet(name string, messages ...string) {
msg := "Hello"
if len(messages) > 0 {
msg = messages[0]
}
fmt.Println(msg, name)
}
// Calls:
greet("Alice") // Hello Alice
greet("Bob", "Hi") // Hi Bob
- Using configuration structures — pass a struct with parameters to the function, where default values can be set upon creation:
type Config struct {
Timeout int
}
func doSomething(cfg Config) {
if cfg.Timeout == 0 {
cfg.Timeout = 30 // default value
}
// ...
}
// Call:
doSomething(Config{})
- Creating helper constructor functions with different sets of parameters.
Thus, in Go, default values are implemented through explicit logic inside the function or through structures, not through language syntax.