I want to have helpers for big maths from big
package. One of them is IsZero
which accepts big.(Int|Float|Rat)
and returns true
if this big number equals to zero and false
if not.
I did it that way:
package main
import (
"fmt"
"math/big"
)
type Target interface {
big.Int | big.Float | big.Rat
}
type Comparable[T Target] interface {
Cmp(*T) int
}
func IsZero[C Comparable[T], T Target](a C) bool {
var t T
return a.Cmp(&t) == 0
}
And it works if I specify generic arguments explicitly:
func main() {
fmt.Println(IsZero[Comparable[big.Int], big.Int](big.NewInt(0)))
}
But if I try to make Go infer them for me, it doesn't work:
func main() {
fmt.Println(IsZero(big.NewInt(0)))
}
./prog.go:25:20: cannot infer T (prog.go:18:30)
Is there a possible workaround for this?
"Is there a possible workaround for this?" No, except hope inference will be smarter in the next Go version. – Volker
Your can only simplify IsZero
function:
func IsZero[T Target](a Comparable[T]) bool {
var t T
return a.Cmp(&t) == 0
}
func main() {
fmt.Println(IsZero[big.Int](big.NewInt(0)))
var b Comparable[big.Int] = big.NewInt(0)
fmt.Println(IsZero(b))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With