Home > Software engineering >  golang error: cannot use generic type without instantiation
golang error: cannot use generic type without instantiation

Time:02-26

Studying golang 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 sublety. 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