In PHP I can create an interface
interface Hello {
public function bar();
}
And some classes that implements it
final class Foo implements Hello {
public function bar() {
// do something
}
}
final class Bar implements Hello {
public function bar() {
// do something
}
}
Then, I can also create a NewClass::bar() method that accept the interface.
final class NewClass {
public function bar(Hello $hello) {
// do something
}
}
How can I do the same, in Golang?
type humanPlayer struct {
name string
}
type botPlayer struct {
name string
}
How can I realize same pattern in golang?
package main
import (
"fmt"
)
type Namer interface {
Name() string
}
type humanPlayer struct {
name string
}
func (h *humanPlayer) Name() string {
return h.name
}
type botPlayer struct {
name string
}
func (b *botPlayer) Name() string {
return b.name
}
func sayName(n Namer) {
fmt.Printf("Hello %s
", n.Name())
}
func main() {
human := &humanPlayer{
name: "bob",
}
bot := &botPlayer{
name: "tom",
}
sayName(human)
sayName(bot)
}