英文:
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
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论