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

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

Susan Sarandon
Susan Sarandon原創
2024-10-28 07:47:30261瀏覽

How to Achieve Generic Programming for 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{}類型實作通用的Get()函數:

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

在客戶端程式碼中,可以將回傳值對應的型別轉換:

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

但是,這種方法由於類型轉換而引入了一些運行時開銷。仍然建議考慮重構程式碼或針對不同類型使用單獨的函數。

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

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