Home  >  Article  >  Backend Development  >  How to Achieve Generic Programming for Variadic Functions in Go?

How to Achieve Generic Programming for Variadic Functions in Go?

Susan Sarandon
Susan SarandonOriginal
2024-10-28 07:47:30261browse

How to Achieve Generic Programming for Variadic Functions in Go?

Generic Programming for Variadic Functions in Go

Despite Go's lack of templates and overloaded functions, it's still possible to implement some form of generic programming for variadic functions.

Consider the following example with a series of functions that retrieve values from a database and return a default value if the requested value is missing:

<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
}</code>

To eliminate the code redundancy, one can implement a generic Get() function using the interface{} type:

<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 0
        }
    }
    return v
}</code>

In the client code, the returned values can be typecasted accordingly:

<code class="go">value := document.Get("index", 1).(int)  // Panics when the value is not int

value, ok := document.Get("index", 1).(int)  // ok is false if the value is not int</code>

However, this approach introduces some runtime overhead due to type conversion. It's still advisable to consider refactoring the code or using separate functions for different types.

The above is the detailed content of How to Achieve Generic Programming for Variadic Functions in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn