Home > other >  Go error: cannot use generic type without instantiation
Go error: cannot use generic type without instantiation

Time:02-27

Studying Go generics, I'm running into an error I can't seem to untangle. I've boiled it down to the simplest code:

type opStack[T any] []T

func main() {

    t := make(opStack)
    //  t := new(opStack)
    t = append(t, 0)
    fmt.Println(t[0])
}

In playground, this bonks at the make() call (and similarly on the new call that's commented out) with the following error message:

cannot use generic type opStack[T any] without instantiation

But make() is an instantiating function. So, I expect I'm missing some syntactical subtlety. What is Go complaining about and what's the needed correction?

CodePudding user response:

because you want

t = append(t, 0)

the data type can be int or float group.

this code should work

package main

import "fmt"

func main() {
    type opStack[T any] []T

    t := make(opStack[int], 0) // You must initialize data type here
    t = append(t, 0)
    fmt.Println(t[0])
}
  • Related