Go版本: 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 (受浮点约束的float64类型的变量)用作other.ReceiveDamage编译器(IncompatibleAssign)的参数中的float64值。
我已经将struct泛型实例化为*Charmander[float64]。我希望编译器知道AttackPower是一个float64。
当我将一个float64传递给一个期望float64的函数时,它为什么要抱怨呢?另一方面,ReceiveDamage不抱怨。我正在从float64中减去一个Health,这是一个受限的类型。
发布于 2022-03-16 07:24:56
您必须使用类型转换。方法ReceiveDamage需要一个float64,但是主类型在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)实例化T时,转换float32可能会导致精度损失。(在这个特定的用例中,这可能不是问题.)
https://stackoverflow.com/questions/71490463
复制相似问题