Suppose I have the following:
type T struct { Name string }
Then I create a var of type T:
thing := T{"Hello World"}
I then reflect the type:
t := reflect.TypeOf(thing) // main.T
Then I pass t
in to a method that accepts an interface, is there any way I can then say, in that method, that the accepted interface{}
is of type main.T
if I have that string?
The use case is I have a json string that fits a type. I have a string of that type (main.T
) and I want to be able to create a new variable that is of type main.t
when I only know of the string, main.T
then marshal the data to that new variable.
The Go runtime does not provide a way to create a value given the name of a type, but that's something you can implement in the application:
var types = map[string]reflect.Type{
"main.T": reflect.TypeOf((*T)(nil)).Elem(),
}
You can create a new value given the name using:
v := reflect.New(types[name]).Interface()
This assumes that name is a valid name. You may want to check for the case where types[name] == nil.
You can also do this without reflection:
var types = map[string]func() interface{} {
"main.T": func() interface{} { return &T{} }
}
v := types[name]()