Last active
August 29, 2015 14:05
-
-
Save alexsaezm/56deee17046860acb0da to your computer and use it in GitHub Desktop.
Interfaces in Go
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
| package main | |
| import ( | |
| "fmt" | |
| ) | |
| type Animal interface { | |
| Speak() string | |
| } | |
| type Cat struct { | |
| name string | |
| } | |
| func (c *Cat) Speak() string { | |
| c.name = "Misifu" | |
| return "meeeeeooooow" | |
| } | |
| func main() { | |
| mycat := Cat{} | |
| fmt.Println(mycat.name + " says: " + mycat.Speak()) | |
| } |
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
| package main | |
| import ( | |
| "fmt" | |
| ) | |
| // Accept empty interface | |
| // All types implements at least zero methods | |
| func emptyInterface(i interface{}) { | |
| switch s := i.(type) { | |
| default: | |
| fmt.Printf("Type: %T\n", s) | |
| } | |
| } | |
| func main() { | |
| a := 42 | |
| emptyInterface(a) | |
| b := "Hello" | |
| emptyInterface(b) | |
| } |
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
| package main | |
| import ( | |
| "fmt" | |
| ) | |
| // Something like inheritance | |
| type Num int | |
| type Number Num | |
| func (n Num) Print() { | |
| fmt.Printf("n+1: %d\n", n+1) | |
| } | |
| func (n Number) Print() { | |
| Num(n).Print() | |
| } | |
| func main() { | |
| var b Number | |
| b = 42 | |
| b.Print() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment