Home  >  Article  >  Backend Development  >  How Can You Achieve Generic Programming with Variadic Functions in Go?

How Can You Achieve Generic Programming with Variadic Functions in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 12:21:29777browse

How Can You Achieve Generic Programming with Variadic Functions in Go?

Generic Programming with Variadic Functions in Go

Despite Go's lack of templates or function overloading, achieving some degree of generic programming for variadic functions is possible.

Consider the following redundant code snippets:

<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 this redundancy, we can utilize 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 nil
        }
    }
    return v
}</code>

This general function can then be used with type assertion in client code:

<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>

However, this approach introduces runtime overhead. It may be more efficient in some cases to retain the separate functions and consider restructuring the code.

The above is the detailed content of How Can You Achieve Generic Programming with 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