Reputation: 395
In Golang, the values in map, can they be types ? For example how do I create a map m[string]type such that it can be like this,
m["abc"] = int
m["def"] = string
m["ghi"] = structtype ( some structure of type structtype)
I need such map because, I have a function which has a string argument and according to that string argument the function creates a variable of a certain type and does some operations. So, if I have a map which maps a string to a type, the function can check that map using the string argument as the key to find out which type of variable it needs to create.
Upvotes: 0
Views: 550
Reputation: 3294
I sounds like you need map[string]reflect.Type
val := map[string]reflect.Type{}{}
val["int"] = reflect.TypeOf(int(0))
pointer_to_new_item := reflect.New(val["int"])
If you need a non-pointer value you then use Indirect
:
new_item := reflect.Indirect(pointer_to_new_item)
Using reflect to create a value will give you a reflect.Value
, which you then need to unpack the actual value you want from using other reflect functions. See The reflect documentation for more info.
Keep in mind that reflect.New
only makes simple types, structures, etc. If you need channels, maps, or slices there are other, similar functions that work like the make
builtin.
Upvotes: 4