Can I create an alias for a generic function? I get error "Cannot use generic function without instantiation"

Issue

I can define a generic function:

package hello

func IsZero[T int64|float64](value T) bool {
   return value == 0
}

Then if I try to alias that function in another package, it fails:

package world

import "hello"

var IsZero = hello.IsZero

The above doesn’t compile with:

cannot use generic function hello.IsZero without instantiation

Instead this works:

var IsZero = hello.IsZero[int64]

Is it possible to do this, using some other syntax?

Solution

If the function is small, like in the question, its probably easier to just
vendor it:

package vendor

func thisIsJustCopy[T int64|float64](value T) bool {
   return value == 0
}

but if the function is big, you can do it like this:

package world
import "hello"

func IsZero[T int64|float64](value T) bool {
   return hello.IsZero(value)
}

Answered By – Zombo

Answer Checked By – Senaida (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.