Home >Backend Development >Golang >Can Go\'s Variadic Functions Be Made More Generic?
While Go may not provide inherent support for generic programming or function overloading, it does allow for some level of flexibility when dealing with variadic functions.
Consider the common scenario where you have multiple functions like the following:
<code class="go">func (this Document) GetString(name string, defaults ...string) string { // ... Function implementation } func (this Document) GetInt(name string, defaults ...int) int { // ... Function implementation }</code>
You may encounter code duplication across these functions. Is there a way to minimize this redundancy?
Yes, while Go lacks generic templates, you can leverage interface{} to provide a generic solution.
<code class="go">func (this Document) Get(name string, defaults ...interface{}) interface{} { // ... Function implementation // This function returns `interface{}` instead of specific types. }</code>
This approach enables you to interact with the function in the following manner:
<code class="go">value := document.Get("index", 1).(int) // Type casting is required</code>
If you prefer null values, you can use this approach:
<code class="go">value, ok := document.Get("index", 1).(int) // Returns `ok` to indicate type compatibility</code>
However, this approach may incur runtime overhead. It's advisable to assess your code structure and determine if separate functions or a different solution is more suitable for your specific needs.
The above is the detailed content of Can Go\'s Variadic Functions Be Made More Generic?. For more information, please follow other related articles on the PHP Chinese website!