Skip to content

Instantly share code, notes, and snippets.

@Gurpartap
Last active August 29, 2015 14:27
Show Gist options
  • Save Gurpartap/47c006bf26aa842bdf75 to your computer and use it in GitHub Desktop.
Save Gurpartap/47c006bf26aa842bdf75 to your computer and use it in GitHub Desktop.
Golang type interface implementation (protocol of Swift)
package main
import "fmt"
// protocol
type Specimen interface {
NumLegs() int
}
var Species = []Specimen{}
// implementation
type Human struct{}
func (h Human) NumLegs() int {
return 2
}
type Cat struct{}
func (c Cat) NumLegs() int {
return 4
}
func init() {
Species = append(Species, Human{})
Species = append(Species, Cat{})
}
func main() {
fmt.Print("Registered species: ")
fmt.Println(len(Species))
fmt.Println("Number of legs of each: ")
for _, specimen := range Species {
fmt.Println(specimen.NumLegs())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment