Home  >  Article  >  Backend Development  >  How Can Go Achieve Generic Variadic Functions Without Templates?

How Can Go Achieve Generic Variadic Functions Without Templates?

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 20:09:02145browse

 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!

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