How Can Go Achieve Generic Variadic Functions Without Templates?

Linda Hamilton
Release: 2024-10-26 20:09:02
Original
156 people have browsed it

 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>
Copy after login

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>
Copy after login

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>
Copy after login

or

<code class="go">value, ok := document.Get("index", 1).(int) // ok is false if the value is not an int</code>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!