Home >Backend Development >Golang >How Can Go Achieve Generic Variadic Functions Without Templates?
Generic Variadic Argumentation in Go
Go lacks templates and overloaded functions, but it offers a solution for attaining a semblance of generic programming in variadic functions.
Challenge:
Numerous functions having similar structures, such as:
<code class="go">func (this Document) GetString(name string, defaults ...string) string { v, ok := this.GetValueFromDb(name) if !ok { if len(defaults) >= 1 { return defaults[0] } else { return "" } } return v.asString } func (this Document) GetInt(name string, defaults ...int) int { v, ok := this.GetValueFromDb(name) if !ok { if len(defaults) >= 1 { return defaults[0] } else { return 0 } } return v.asInt } // etc. for various types</code>
Solution:
Utilizing the interface{} type enables a generic function:
<code class="go">func (this Document) Get(name string, defaults ...interface{}) interface{} { v, ok := this.GetValueFromDb(name) if !ok { if len(defaults) >= 1 { return defaults[0] } else { return nil } } return v }</code>
The GetValueFromDb function should return an interface{} as well. In client code, values can be converted and attained using type assertion:
<code class="go">value := document.Get("index", 1).(int) // Panics if the value is not an int</code>
or
<code class="go">value, ok := document.Get("index", 1).(int) // ok is false if the value is not an int</code>
Although this introduces some runtime overhead, restructuring the code and separating functions may be more efficient.
The above is the detailed content of How Can Go Achieve Generic Variadic Functions Without Templates?. For more information, please follow other related articles on the PHP Chinese website!