I have done the following:
- Defined a “Parent” interface with Display() fn.
- Created 2 Child structs which implement their respective Display() fn.
- In main(), created 2 child objects and added them to :
availableObjs[]interface{}
- Now, in For loop, want to take the object and call its respective Display() function. This is where I am struck at.
GoPlayground Code : https://play.golang.org/p/jdHpueokrEk
Same Code inline :
package main
import (
"fmt"
"reflect"
)
////// Parent Interface which has Display() fn.
type Parent interface {
Display()
}
// 2 Child structs implementing their Display() fn.
type Child1 struct {
name1 string
}
type Child2 struct {
name2 string
}
func (c1 Child1) Display() {
fmt.Println("c1Name : ", c1.name1)
}
func (c2 Child2) Display() {
fmt.Println("c2Name : ", c2.name2)
}
////////////////////////////////////////////
// Maintains the created objects
var availableObjs []interface{}
func main() {
//// Creating 2 objects
c1 := Child1{"Child1"}
c2 := Child2{"Child2"}
// Adding 2 objects to availableObjs
availableObjs = append(availableObjs, c1)
availableObjs = append(availableObjs, c2)
// Now, want to fetch the Object from Interface and call its respective Display() fn.
for _, obj := range availableObjs {
fmt.Println("")
fmt.Println("Obj Got = ",obj)
fmt.Println("Obj type = ",reflect.TypeOf(obj))
//obj.Display() // <-- Problem Line
}
}