I want to define an interface that has a method that returns a value whose type is the interface itself.
I tried to define the interface like this:
type Event interface {
}
type Entity interface {
ApplyEvent(command Event) (Entity, error)
}
And I would like to make a struct implement the Entity interface by doing:
type ShoppingList struct {
}
func (list ShoppingList) ApplyEvent(event Event) (ShoppingList, error) {
// code that changes "list" goes here.
return list, nil
}
If I do that and then try to pass a ShoppingList to a function that expects an Entity I get the following error:
func main() {
test(ShoppingList{})
}
func test(e Entity) {
}
Cannot use 'ShoppingList{}' (type ShoppingList) as type Entity.
Type does not implement 'Entity'
need method: ApplyEvent(command Event) (Entity, error)
have method: ApplyEvent(event Event) (ShoppingList, error)
I know I could define the interface and the receiver like this instead:
type Event interface {
}
type Entity interface {
ApplyEvent(command Event) error
}
type ShoppingList struct {
}
func (list *ShoppingList) ApplyEvent(event Event) error {
// code that changes "list" goes here.
return nil
}
But I would prefer to write the code using pure functions and immutable data structures as much as possible.
I want to return the changed value instead of mutating the receiver.
What would be the way to do it in Go?