In the code below, I'm trying to create concrete implementations of a Model interface and API interface:
package main
import "fmt"
/////////
type Model interface {
ID() string
}
type API interface {
Create(Model)
}
/////////
type ConcreteModel struct {}
func (model ConcreteModel) ID() string {
return "123"
}
func (model ConcreteModel) Name() string {
return "aron"
}
type ConcreteAPI struct{}
func (api ConcreteAPI) Create(model ConcreteModel) {
fmt.Println("Created concrete model with id " + model.ID() + ", name " + model.Name())
}
func main() {
// invocation via interface
func(api API) {
api.Create(ConcreteModel{})
}(ConcreteAPI{})
}
Utterly confusing to me is why I get the following error when running this code:
ConcreteAPI does not implement API (wrong type for Create method)
have Create(ConcreteModel)
want Create(Model)
From what I glean about golang ducktyping, it would seem that ConcreteAPI should be fulfilling the contract of Create(Model) because ConcreteModel
has the required methods of Model
, namely ID() string
.
The reason I want to try to do something like this is that func(api API)
is a stand-in for something that knows how to play with concrete API implementations, in my intended real-world codebase.
Does anybody have suggestions on how to make whats above actually work?
ConcreteAPI doesn't implements API's method ,please you can add:
func( concreteApi *ConcreteAPI ) Create(Model){}
but you have another error see detail below: ConcreteModel also doesn't implements Model