Last active
August 29, 2015 14:27
-
-
Save Gurpartap/47c006bf26aa842bdf75 to your computer and use it in GitHub Desktop.
Golang type interface implementation (protocol of Swift)
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" | |
// 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