Skip to content

Instantly share code, notes, and snippets.

@YanhaoYang
Created July 5, 2017 07:22
Show Gist options
  • Save YanhaoYang/25f8b0bef47a2c8f58989ff645a85973 to your computer and use it in GitHub Desktop.
Save YanhaoYang/25f8b0bef47a2c8f58989ff645a85973 to your computer and use it in GitHub Desktop.
golang-polymorphism
// https://play.golang.org/p/CpPW7CxYBV
package main
import (
"fmt"
)
type A struct {
X string
}
func (a *A) hi() {
fmt.Println(a.X)
}
type B struct {
A
Y string
}
func (b *B) hi() {
fmt.Println(b.Y)
}
type C struct {
A
Y string
}
type Hi interface {
hi()
}
func say(hi Hi) {
hi.hi()
}
func main() {
a := &A{X: "X in a"}
say(a)
b := &B{Y: "Y in b"}
b.X = "X in b"
say(b)
c := C{}
c.X = "X in c"
say(&c)
}
// X in a
// Y in b
// X in c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment