Go不将func识别为有效的接口。

huangapple go评论82阅读模式
英文:

Go does not recognize a func as a valid interface

问题

我有一个函数:

func(context.Context, *domain.Scorecard) (*domain.Scorecard, error)

我想将其作为参数传递给一个接口:

type warehouse interface {
   Get(context.Context, *domain.Scorecard) (*domain.Scorecard, error)
}

例如:

warehouseMock := usecase.WithScenarioFinder(
  func(player *domain.Player) (*domain.Scenario, error) {
    return nil, nil
  }
)

传统的方法是创建一个具有Get方法的结构体,但我很好奇是否存在一种方式可以告诉"嘿,这是一个简单的函数,与原来的签名相同(没有名称),接受它"。

英文:

I have the func

func(context.Context, *domain.Scorecard) (*domain.Scorecard, error)

And i want pass this as a param that receive a interface

warehouse interface {
   Get(context.Context, *domain.Scorecard) (*domain.Scorecard, error)
}

Ex:

warehouseMock := 
usecase.WithScenarioFinder(
  func(player *domain.Player) (*domain.Scenario, error) {
		  return nil,nil
)

The traditional form is create a struct that have the method Get, but i have curiosity if exist the way to tell "hey, that is a simple func, is the same firm (with no name), accept it"

答案1

得分: 4

函数不会实现只有一个相同签名方法的接口。请参阅此Go问题以了解有关该主题的讨论。

创建一个适配器类型将函数转换为接口:

type WarehouseFunc func(context.Context, *domain.Scorecard) (*domain.Scorecard, error)

func (f WarehouseFunc) Get(c context.Context, d *domain.Scorecard) (*domain.Scorecard, error) {
   return f(c, d)
}

像这样将匿名函数转换为接口:

itf = WarehouseFunc(func(c context.Context, d *domain.Scorecard) (*domain.Scorecard, error) {
    return nil, nil
})
英文:

Functions do not implement interfaces with only a single method of that same signature. See this Go issue for a discussion on the topic.

Create an adaptor type to convert a function to an interface:

type WarehouseFunc func(context.Context, *domain.Scorecard) (*domain.Scorecard, error)

func (f WarehouseFunc) Get(c context.Context, d *domain.Scorecard) (*domain.Scorecard, error) {
   return f(c, d)
}

Convert an anonymous function to an interface like this:

itf = WarehouseFunc(func(c context.Context, d *domain.Scorecard) (*domain.Scorecard, error) {
    return nil, nil
})

huangapple
  • 本文由 发表于 2021年11月9日 00:30:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/69886817.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定