Skip to content

Instantly share code, notes, and snippets.

@alexsaezm
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save alexsaezm/56deee17046860acb0da to your computer and use it in GitHub Desktop.

Select an option

Save alexsaezm/56deee17046860acb0da to your computer and use it in GitHub Desktop.
Interfaces in Go
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())
}
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)
}
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