Created
January 31, 2017 13:27
-
-
Save tmiele/26dae300da1022b52ad0da2492750abf to your computer and use it in GitHub Desktop.
golang slice range polymorphism interface
This file contains 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 Human interface { | |
myStereotype() string | |
sex() string | |
} | |
type Man struct { | |
} | |
func (m Man) myStereotype() string { | |
return "I'm going fishing." | |
} | |
func (m Man) sex() string { | |
return "male" | |
} | |
type Woman struct { | |
} | |
func (w Woman) myStereotype() string { | |
return "I'm going shopping." | |
} | |
func (w Woman) sex() string { | |
return "female" | |
} | |
type Child struct { | |
sexe string | |
} | |
func (c Child) myStereotype() string { | |
return "I'm playing video games." | |
} | |
func (c Child) sex() string { | |
return c.sexe | |
} | |
func main() { | |
m := new(Man) | |
w := new(Woman) | |
c := new(Child) | |
c.sexe = "boy" | |
hArr := []Human{m, w} | |
hArr = append(hArr, c) | |
for n, h := range hArr { | |
fmt.Println("I'm a human, and my stereotype is: ", hArr[n].myStereotype(), " I am a", h.sex()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment