Object added to []interface{}. Now need to fetch the object and call the Object's respective Display() fn

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 
	}
}

Why are you using an interface{} slice instead of a Parent one? You can certainly type assert them and then call Display like this:

for _, obj := range availableObjs {
		p := obj.(Parent)
		p.Display()
}

But the obvious way to go is to simply use a Parent slice:

r availableObjs []Parent

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 {
		obj.Display()
	}
}

2 Likes

Both worked for me. Will pick Option 2. Thanks for the help!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.