Please check the below program. Var z
is of type interface{}
. It stores the type of struct X
. But I cannot use it to create a new instance of X
. I have some requirement where I need to keep the type of the object in an interface{}
variable, and use that to create an instance of that type. Here is a link for the snippet on go playground
package main
import (
"fmt"
"reflect"
)
type X struct {
a int
b int
}
type MyInt int
func main() {
x := X{}
y := reflect.TypeOf(x)
fmt.Printf("%v
", reflect.New(y))
var z interface{}
z = y
fmt.Printf("%v
", z) // prints main.X
//Below line throws the error
fmt.Printf("%v
", reflect.New(z)) //----> This line throws error
}
You can use type assertion to extract the reflect.Type
value from an interface{}
value:
fmt.Printf("%v
", reflect.New(z.(reflect.Type))) //----> Works!
Your modified example on the Go Playground.
Note that the above example panics if z
does not hold a value of type reflect.Type
or if it is nil
. You can use the special comma-ok form to prevent that:
if t, ok := z.(reflect.Type); ok {
fmt.Printf("%v
", reflect.New(t)) // t is of type reflect.Type
} else {
fmt.Println("Not the expected type or nil!")
}