Home >Backend Development >Golang >How to Pass Constrained Types as Function Arguments in Go 1.18 Generics?
Handling Constrained Types as Function Arguments in Go 1.18 Generics
Go 1.18 introduced generics, allowing developers to create functions and types that operate on arbitrary data types. However, when trying to pass a constrained type as an argument to a function that expects a concrete type, the compiler may raise an error.
To illustrate this issue, consider the following example:
<code class="go">type Pokemon interface { ReceiveDamage(float64) InflictDamage(Pokemon) } type Float interface { float32 | float64 } type Charmander[F Float] struct { Health F AttackPower F }</code>
Here, Charmander implements the Pokemon interface and accepts a generic type parameter F that must be either float32 or float64.
<code class="go">func (c *Charmander[float64]) ReceiveDamage(damage float64) { c.Health -= damage } func (c *Charmander[float64]) InflictDamage(other Pokemon) { other.ReceiveDamage(c.AttackPower) }</code>
However, the compiler raises an error in the InflictDamage method, stating that c.AttackPower cannot be used as a float64 argument for the other.ReceiveDamage function. This is because, despite instantiating the Charmander struct as *Charmander[float64], the compiler still considers AttackPower to be of type F.
The solution to this issue lies in using type conversions. ReceiveDamage expects a float64, but AttackPower is still constrained to F. Therefore, we need to convert AttackPower to 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>
These conversions compile because float64 is convertible to all types in the type set of F (float32 and float64).
Note that the conversion T(damage) may result in precision loss if T is instantiated with float32. However, this is unlikely to be a concern in this specific use case.
The above is the detailed content of How to Pass Constrained Types as Function Arguments in Go 1.18 Generics?. For more information, please follow other related articles on the PHP Chinese website!