'Function type cannot have type parameters

I am trying to write a sample program to try and implementing the a data structure using go generic proposed in go2.

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

package collection

type Iterator interface {
    //ForEachRemaining Performs the given action for each remaining element until all elements have been processed or
    //the action throws an error.
    ForEachRemaining(action func[T any](T) error) error

    //HasNext returns true if the iteration has more elements.
    HasNext() bool

    //Next returns the next element in the iteration.
    Next() error

    //Remove removes from the underlying collection the last element returned by this iterator (optional operation).
    Remove() error
}

It keeps giving me following error

function type cannot have type parameters

Is there any way to define generic interface



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 blackgreen