Skip to content

Instantly share code, notes, and snippets.

@kardolus
Last active November 30, 2019 18:32
Show Gist options
  • Save kardolus/38ca36c043a8f14cf8e8e80e9e7f66ec to your computer and use it in GitHub Desktop.
Save kardolus/38ca36c043a8f14cf8e8e80e9e7f66ec to your computer and use it in GitHub Desktop.
playing with reflection and interfaces
package main
import (
"fmt"
"reflect"
)
type Animal interface {
Move()
}
type Dog struct {
Name string
Age int
}
func (d Dog) Move() {
fmt.Println("Dog moving")
}
type Cat struct {
Name string
Age int
}
func (c Cat) Move() {
fmt.Println("Cat moving")
}
func main() {
var dog = Dog{
Name: "Skittles",
Age: 3,
}
var cat = Cat{
Name: "Felix",
Age: 5,
}
fmt.Printf("dog: %+v\n", dog)
fmt.Printf("cat: %+v\n", cat)
doAnimalStuff(dog)
doAnimalStuff(cat)
dogType := reflect.TypeOf(dog)
fmt.Println("The dog type:", dogType)
animals := []Animal{dog, cat}
doLotsOfAnimalStuff(animals)
doInterfaceStuff(dog)
}
func doAnimalStuff(a Animal) {
a.Move()
animalType := reflect.TypeOf(a) // main.Dog or main.Cat
fmt.Println("The animal type:", animalType)
structValue := reflect.ValueOf(a) // {Name:Felix Age:5}
fmt.Printf("structValue %+v\n", structValue)
for j := 0; j < animalType.NumField(); j++ { // iterate over struct fields
field := animalType.Field(j) // {Name:Name PkgPath: Type:string Tag: Offset:0 Index:[0] Anonymous:false}
fmt.Printf("field: %+v\n", field)
fieldName := field.Name // Name or Age
fieldType := field.Type.Name() // string or int
fmt.Println("fieldName - fieldType", fieldName, "-", fieldType)
fieldValue := structValue.FieldByName(fieldName) // Felix or 5
fmt.Printf("fieldValue %+v\n", fieldValue)
}
fmt.Println(">>>>>>>")
}
func doLotsOfAnimalStuff(animals []Animal) {
fmt.Println("doLotsOfAnimalStuff")
for _, animal := range animals {
doAnimalStuff(animal)
}
}
func doInterfaceStuff(in interface{}) {
fmt.Println("doInterfaceStuff")
animal := in.(Animal)
doAnimalStuff(animal)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment