Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic type inference with dependent types in Go [duplicate]

Tags:

generics

go

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?

like image 456
Alexey Shekhirin Avatar asked Oct 18 '25 10:10

Alexey Shekhirin


1 Answers

"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))
}
like image 164
kozmo Avatar answered Oct 21 '25 00:10

kozmo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!