首頁  >  文章  >  後端開發  >  Go 的可變參數函數可以變得更通用嗎?

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

Susan Sarandon
Susan Sarandon原創
2024-10-27 19:57:30957瀏覽

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

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