Skip to content

Instantly share code, notes, and snippets.

@mprymek
Created February 25, 2018 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mprymek/84220c24df25278379dded1e9e9806d5 to your computer and use it in GitHub Desktop.
Save mprymek/84220c24df25278379dded1e9e9806d5 to your computer and use it in GitHub Desktop.
/*
Golang's methods are not "virtual" or "overridable".
Don't expect OOP-like inheritance, use composition instead.
Try it here: https://play.golang.org/p/DujbnuHDZAW
*/
package main
import "fmt"
type Node interface {
GetID() string
Print()
}
/* THIS IS WRONG */
type BasicNodeWrong struct {
}
func (n BasicNodeWrong) Print() {
fmt.Printf("My ID is %s\n", n.GetID())
}
func (n BasicNodeWrong) GetID() string {
return "[Internal error - GetID called on BasicNodeWrong]"
}
type SpecialNodeWrong struct {
*BasicNodeWrong
ID string
}
func (n SpecialNodeWrong) GetID() string {
return n.ID
}
func NewSpecialNodeWrong(ID string) *SpecialNodeWrong {
return &SpecialNodeWrong{
&BasicNodeWrong{},
ID,
}
}
/* THIS IS RIGHT */
type Identifier interface {
GetID() string
}
type BasicIdentifier struct {
ID string
}
func (id BasicIdentifier) GetID() string {
return "basic:"+id.ID
}
type SpecialIdentifier struct {
*BasicIdentifier
}
func (id SpecialIdentifier) GetID() string {
return "special:"+id.ID
}
type NodeRight struct {
ID Identifier
}
func (n NodeRight) GetID() string {
return n.ID.GetID()
}
func (n NodeRight) Print() {
fmt.Printf("My ID is %s\n", n.ID.GetID())
}
func NewBasicNode(ID string) *NodeRight {
return &NodeRight{
&BasicIdentifier{ID},
}
}
func NewSpecialNode(ID string) *NodeRight {
return &NodeRight{
&SpecialIdentifier{&BasicIdentifier{ID}},
}
}
func main() {
var n Node = NewSpecialNodeWrong("1")
n.Print()
var bn Node = NewBasicNode("2")
bn.Print()
var sn Node = NewSpecialNode("3")
sn.Print()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment