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

Time:03-19

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?

CodePudding user response:

That's not an alias. And you already have your answer, actually. But if you want a formal reference, from the language specs, Instantiations:

A generic function that is is not called requires a type argument list for instantiation

So when you attempt to initialize a variable of function type, the function hello.IsZero is not called, and therefore requires instantiation with specific type parameters:

// not called, instantiated with int64
var IsZero = hello.IsZero[int64]

At this point the variable (let's give it a different name for clarity) zeroFunc has a concrete function type:

    var zeroFunc = IsZero[int64]
    fmt.Printf("type: %T\n", zeroFunc) 

Prints:

type: func(int64) bool

CodePudding user response:

I try to alias that function in another package

Aliases work for types only. Your code just tries to declare a variable.

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

No.

CodePudding user response:

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)
}
  • Related