【问题标题】:Function type cannot have type parameters函数类型不能有类型参数
【发布时间】:2021-01-19 05:00:39
【问题描述】:

我正在尝试编写一个示例程序来尝试使用 go2 中提出的 go generic 来实现数据结构。

作为其中的一部分,我想定义一个迭代器接口。我有以下代码:

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
}

它一直给我以下错误

function type cannot have type parameters

有什么方法可以定义泛型接口

【问题讨论】:

    标签: go generics interface


    【解决方案1】:

    正如错误提示的那样,methods cannot have type parameters 是他们自己根据最新设计的。但是,它们可以使用它们所属的接口和结构中的泛型。

    您需要在接口级别定义类型(即type Iterator[T any] interface),然后将T 用作接口主体内方法中的任何其他类型。

    package main
    
    import "fmt"
    
    type Iterator[T any] 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) 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
    }
    
    func main() {
        fmt.Println("This program is valid")
    }
    
    

    试试go2 playground

    【讨论】:

      猜你喜欢
      • 2020-01-23
      • 1970-01-01
      • 2022-01-21
      • 2018-12-30
      • 2016-02-06
      • 2014-01-12
      • 2021-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多