gogenericstypestype-systems

Go: Assignment of type aliases for generics


I have type that receives generic

After it, i create type alias with filled generic type

When i try to assign variable typed with type alias to the same type i receive following error:

cannot use y (variable of type TInt) as TGeneric[int] value in variable declaration [IncompatibleAssign]

type TGeneric[T any] struct {
  field T
}
type TInt TGeneric[int]

func init()  {
  var y TInt
  var x TGeneric[int] = y
}

I found this out when trying to pass value to the function as follows:

type TGeneric[T any] struct {
  field T
}
type TInt TGeneric[int]

func funcExample[T any](arg TGeneric[T]) {}

func init()  {
  var y TInt

  funcExample(y)
  // in call to funcExample, type TInt of y
  // does not match TGeneric[T] (cannot infer T)
  // [CannotInferTypeArgs]
}

I tried hardcoding type to function call, but it didn't help

type TGeneric[T any] struct {
  field T
}
type TInt TGeneric[int]

func funcExample[T any](arg TGeneric[T]) {}

func init()  {
  var y TInt

  funcExample[int](y)
  // cannot use y (variable of type TInt) as 
  // TGeneric[int] value in argument to funcExample[int]
  // [IncompatibleAssign]
}

Why it happens and what workarounds are there?


Solution

  • The statement:

    type TInt TGeneric[int]
    

    defines a new type TInt that is distinct from TGeneric[int]. Fix by using a type alias:

    type TInt = TGeneric[int]
    

    Playground Example