0

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.

user1851006
  • 365
  • 1
  • 4
  • 12

1 Answers1

4

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.

Milo Christiansen
  • 3,204
  • 2
  • 23
  • 36
  • 1
    in your example, instead of int, if it is a struct type, do I have to create a random struct variable of that type to reflect it's value ? – user1851006 Jul 27 '17 at 21:11
  • 1
    Yes, but you only have to do it when populating the map, so it only has to be done once. – RayfenWindspear Jul 27 '17 at 21:12
  • 2
    You must also note, that the code in this answer will give you a `reflect.Value`, not an `int`. There is extra `reflect` stuff involved to make it an actual `int` or `struct` or whatever it is. – RayfenWindspear Jul 27 '17 at 21:14
  • Very true, that is one of the reasons I made sure to link to the docs. I should probably have put that in the answer. I'll edit it. – Milo Christiansen Jul 27 '17 at 21:20
  • @MiloChristiansen It's the reason I flagged as a duplicate to one I answered that was the exact same question. You answer is good and nicely concise, but I wanted to make sure to link to other resources as well. – RayfenWindspear Jul 27 '17 at 21:41
  • I just realized that what I get is not a struct but an interface which I need to convert into the struct. That's just meaningless because if I knew the struct , then I'd directly define a variable instead of using all this. – user1851006 Jul 27 '17 at 23:47
  • Well, sadly this is the best you can do. If you don't know the struct you need to use reflection to access it anyway, so it is not a problem in practice. – Milo Christiansen Jul 27 '17 at 23:54