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

Barbara Streisand
Release: 2024-10-26 12:21:29
Original
795 people have browsed it

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

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

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

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!

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!