How to Achieve Generic Programming for Variadic Functions in Go?

Susan Sarandon
Release: 2024-10-28 07:47:30
Original
258 people have browsed it

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

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

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

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!

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!