Home > Back-end >  Go does not recognize a func as a valid interface
Go does not recognize a func as a valid interface

Time:11-09

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"

CodePudding user response:

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
})
  • Related