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\n", reflect.New(y))
var z interface{}
z = y
fmt.Printf("%v\n", z) // prints main.X
//Below line throws the error
fmt.Printf("%v\n", reflect.New(z)) //----> This line throws error
}
Aucun commentaire:
Enregistrer un commentaire