去版本:1.18這是一個不是特別有用的愚蠢示例。我將其用作學習泛型的練習。我有一個Pokemon界面type Pokemon interface { ReceiveDamage(float64) InflictDamage(Pokemon)}并Charmander帶有實現Pokemon接口的類型參數。type Float interface { float32 | float64}type Charmander[F Float] struct { Health F AttackPower F}我想用Charmander的攻擊力造成傷害。func (c *Charmander[float64]) ReceiveDamage(damage float64) { c.Health -= damage}func (c *Charmander[float64]) InflictDamage(other Pokemon) { other.ReceiveDamage(c.AttackPower)}我的編譯器報錯不能將 c.AttackPower(受 Float 約束的 float64 類型變量)用作 other.ReceiveDamage 編譯器(IncompatibleAssign)參數中的 float64 值我已經將 struct generic 實例化為*Charmander[float64]. 我希望編譯器知道AttackPower是一個float64.當我將 a 傳遞給float64期望為 的函數時,float64它為什么要抱怨?另一方面,ReceiveDamage不抱怨。我float64從中減去 aHealth是一個受約束的類型。
1 回答

海綿寶寶撒
TA貢獻1809條經驗 獲得超8個贊
您必須使用類型轉換。該方法ReceiveDamage需要一個float64,但主要類型在F. 某種類型的東西F,即使僅限于浮點數,或者即使僅限于一個特定的浮點數,也不是float64。它是F。(此外,它也可以用 實例化float32)。
兩種轉換都可以編譯,因為float64可轉換為類型參數的類型集中的所有類型,float32和float64,反之亦然。
所以方法變成:
func (c *Charmander[T]) ReceiveDamage(damage float64) {
c.Health -= T(damage)
}
func (c *Charmander[T]) InflictDamage(other Pokemon) {
other.ReceiveDamage(float64(c.AttackPower))
}
固定游樂場:https ://go.dev/play/p/FSsdlL8tBLn
當用 實例化時,請注意轉換T(damage)可能會導致精度損失。(在這個特定的用例中,這可能不是問題……)Tfloat32
- 1 回答
- 0 關注
- 126 瀏覽
添加回答
舉報
0/150
提交
取消