首頁  >  文章  >  後端開發  >  如何在 Go 中使用可變參數函數實現泛型程式設計?

如何在 Go 中使用可變參數函數實現泛型程式設計?

Barbara Streisand
Barbara Streisand原創
2024-10-26 12:21:29777瀏覽

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

Go 中使用可變參數函數進行泛型編程

儘管Go 缺乏模板或函數重載,但實現某種程度的可變參數函數泛型程式設計是可能的。

考慮以下冗餘程式碼片段:

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

為了消除這個冗餘,我們可以利用interface{} 類型:

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

然後可以將這個通用函數與type 一起使用客戶端程式碼中的斷言:

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

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

但是,這種方法會引入運行時開銷。在某些情況下,保留單獨的函數並考慮重構程式碼可能會更有效。

以上是如何在 Go 中使用可變參數函數實現泛型程式設計?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn