Skip to content

Instantly share code, notes, and snippets.

@mprymek
Last active February 25, 2018 11:23
Show Gist options
  • Save mprymek/b0045aaf3d8cc01e85934c3b8ac45c4e to your computer and use it in GitHub Desktop.
Save mprymek/b0045aaf3d8cc01e85934c3b8ac45c4e to your computer and use it in GitHub Desktop.
/*
Basic Golang struct embedding example
Try it here: https://play.golang.org/p/HGfzu4m6AB8
*/
package main
import (
"fmt"
)
type Printer interface {
Print()
}
type PrettyPrinter interface {
PrettyPrint()
}
func PrintAny(x interface{}) {
switch x2 := x.(type) {
case PrettyPrinter:
x2.PrettyPrint()
case Printer:
x2.Print()
default:
fmt.Printf("fallback: %v\n", x2)
}
}
type Node interface{}
type BasicNode struct {
ID string
}
type SpecialNode struct {
*BasicNode
}
func (n SpecialNode) Print() {
fmt.Printf("Print: %s\n", n.ID)
}
type PrettyNode struct {
*SpecialNode
}
func (n PrettyNode) PrettyPrint() {
fmt.Printf("PrettyPrint: %s\n", n.ID)
}
func printer(n Node) {
PrintAny(n)
}
func main() {
n := &BasicNode{"Node-1"}
PrintAny(n)
printer(n)
sn := &SpecialNode{&BasicNode{"SpecialNode-1"}}
PrintAny(sn)
printer(sn)
pn := &PrettyNode{&SpecialNode{&BasicNode{"PrettyNode-1"}}}
PrintAny(pn)
printer(pn)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment