Go Generics – How to Use a Type Parameter in an Interface Method

genericsgointerface

I am trying to write a sample program to try and implementing the a data structure using Go generics.

As part of this I want to define a iterator interface. I have the following code:

package collection

type Iterator interface {
    ForEachRemaining(action func[T any](T) error) error
    // other methods
}

It keeps giving me following error

function type cannot have type parameters

Moving the type parameter to the method also doesn't work:

type Iterator interface {
    ForEachRemaining[T any](action func(T) error) error
    // other methods
}

Gives error:

methods cannot have type parameters

Is there any way to define generic interface

Best Answer

As the error suggests, methods cannot have type parameters of their own as per the latest design. However, they can use the generics from the interface or struct they belong to.

What you need is to specify the type parameter on the interface type as follows:

type Iterator[T any] interface {
    // ...
}

and then use the T as any other type parameter in methods within the interface body. For example:

package main

import "fmt"

type Iterator[T any] interface {
    ForEachRemaining(action func(T) error) error
    // other methods
}

func main() {
    fmt.Println("This program compiles")
}

Try it on Go playground.