Created
July 5, 2017 07:22
-
-
Save YanhaoYang/25f8b0bef47a2c8f58989ff645a85973 to your computer and use it in GitHub Desktop.
golang-polymorphism
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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