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

Go 的可變參數函數可以變得更通用嗎?

Susan Sarandon
發布: 2024-10-27 19:57:30
原創
955 人瀏覽過

 Can Go's Variadic Functions Be Made More Generic?

促進Go 中的泛型可變參數函數

雖然Go 可能不提供對泛型編程或函數重載的固有支持,但它在處理可變參數時確實允許一定程度的彈性函數。

考慮一下常見場景,您有多個函數,如下所示:

<code class="go">func (this Document) GetString(name string, defaults ...string) string {
    // ... Function implementation
}

func (this Document) GetInt(name string, defaults ...int) int {
    // ... Function implementation
}</code>
登入後複製

您可能會遇到這些函數之間的程式碼重複。有沒有辦法最大限度地減少這種冗餘?

是的,雖然 Go 缺乏通用模板,但您可以利用 interface{} 來提供通用解決方案。

<code class="go">func (this Document) Get(name string, defaults ...interface{}) interface{} {
    // ... Function implementation
    // This function returns `interface{}` instead of specific types.
}</code>
登入後複製

這種方法使您能夠進行交互按以下方式使用該函數:

<code class="go">value := document.Get("index", 1).(int) // Type casting is required</code>
登入後複製

如果您喜歡空值,可以使用此方法:

<code class="go">value, ok := document.Get("index", 1).(int) // Returns `ok` to indicate type compatibility</code>
登入後複製

但是,此方法可能會產生運行時開銷。建議評估您的程式碼結構並確定單獨的函數或不同的解決方案是否更適合您的特定需求。

以上是Go 的可變參數函數可以變得更通用嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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