首頁 > 後端開發 > Golang > 主體

Go如何在沒有模板的情況下實現通用可變參數函數?

Linda Hamilton
發布: 2024-10-26 20:09:02
原創
156 人瀏覽過

 How Can Go Achieve Generic Variadic Functions Without Templates?

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
}

// etc. for various types</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>
登入後複製

GetValueFromDb函式也應該回傳一個interface{}。在客戶端程式碼中,可以使用型別斷言來轉換和取得值:

<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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!