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

在 Go 函數中使用約束類型作為參數時如何解決類型錯誤?

Patricia Arquette
發布: 2024-10-27 02:43:03
原創
160 人瀏覽過

How to Resolve Type Errors When Using Constrained Types as Arguments in Go Functions?

在函數中使用約束類型作為參數

在Go 1.18 中,泛型提供了一種使用類型參數定義類型的方法,將其約束為特定類型套。但是,當使用約束類型作為需要具體類型的函數的參數時,您可能會遇到錯誤。讓我們探索使用類型轉換的解決方案。

考慮提供的範例:

<code class="go">type Pokemon interface {
    ReceiveDamage(float64)
    InflictDamage(Pokemon)
}

type Float interface {
    float32 | float64
}

type Charmander[F Float] struct {
    Health      F
    AttackPower F
}

func (c *Charmander[float64]) ReceiveDamage(damage float64) {
    c.Health -= damage
}

func (c *Charmander[float64]) InflictDamage(other Pokemon) {
    other.ReceiveDamage(c.AttackPower)
}</code>
登入後複製

當您嘗試編譯此程式時,您會遇到錯誤,因為c.AttackPower 的類型為F限制為float64,但other.ReceiveDamage () 需要float64 參數。

要解決此問題,您需要將 c.AttackPower 明確轉換為滿足 Float 的特定類型。在這種情況下,float32 和 float64 都符合約束,因此您可以轉換為其中任何一個。

更新後的方法變成:

<code class="go">func (c *Charmander[T]) ReceiveDamage(damage float64) {
    c.Health -= T(damage)
}

func (c *Charmander[T]) InflictDamage(other Pokemon) {
    other.ReceiveDamage(float64(c.AttackPower))
}</code>
登入後複製

透過這些轉換,程式將成功編譯。請注意,實例化 Charmander 類型時,必須指定 F 應該綁定的具體類型,如 *Charmander[float64].

以上是在 Go 函數中使用約束類型作為參數時如何解決類型錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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