去版本:1.18
这是一个愚蠢的例子,并不是特别有用。我用它作为学习泛型的练习。
我有一个Pokemon界面
type Pokemon interface {
ReceiveDamage(float64)
InflictDamage(Pokemon)
}
Run Code Online (Sandbox Code Playgroud)
并Charmander带有实现Pokemon接口的类型参数。
type Float interface {
float32 | float64
}
type Charmander[F Float] struct {
Health F
AttackPower F
}
Run Code Online (Sandbox Code Playgroud)
我想利用Charmander的攻击力来造成伤害。
func (c *Charmander[float64]) ReceiveDamage(damage float64) {
c.Health -= damage
}
func (c *Charmander[float64]) InflictDamage(other Pokemon) {
other.ReceiveDamage(c.AttackPower)
}
Run Code Online (Sandbox Code Playgroud)
我的编译器给出错误
无法使用 c.AttackPower(受 Float 约束的 float64 类型变量)作为 other.ReceiveDamage 编译器参数中的 float64 值(IncompleteAssign)
我已经将 struct generic 实例化为*Charmander[float64]. 我希望编译器知道AttackPower是一个float64.
当我将 a …
使用 Go 1.18 中的新泛型,我认为可以创建一个“Either[A,B]”类型,该类型可用于表达某物可以是 A 类型或 B 类型。
您可能会使用此功能的情况是函数可能返回两个可能值之一作为结果(例如,一个表示“正常”结果,一个表示错误)。
我知道 Go 处理错误的“惯用”方式是返回“正常”值和错误值,对于错误或值返回 nil。但是……让我有点困扰的是,我们本质上是在类型中说“这返回 A和B”,而我们真正想说的是“这返回 A或B”。
所以我想也许我们可以在这里做得更好,我认为这也可能是一个很好的练习,可以看到/测试我们可以用这些新泛型做的事情的界限。
可悲的是,尽我所能,到目前为止我还没有能够解决这个练习并让任何东西工作/编译。从我一次失败的尝试来看,这是一个我想以某种方式实现的接口:
//A value of type `Either[A,B]` holds one value which can be either of type A or type B.
type Either[A any, B any] interface {
// Call either one of two functions depending on whether the value is an A or B
// and return the result.
Switch[R any]( // <=== ERROR: interface methods must have no …Run Code Online (Sandbox Code Playgroud)