'Mapping concrete types

What is the idiomatic way to define something like map[type]interface{}?

As far I can see the type (as keyword) is not something comparable so can not be used as a key in a map. Maybe I'm going in the wrong way, so U would accept any suggestion.

TL;DR;

Example motivation

Let's assume in the application model I have type called Person, being stored in a table named "person" of a rdbms.

If I would like to link the entity object Person to the the table name. Things that by definition doens't come together, so it is wise to avoid polluting the Person struct with "not-naturally-related" (this is where my java-OO-based mind appears) [pointer|value]-recieve methods, so a map could be in handy here, right? (maps are great for associating things from differents worlds or sets, right?)

var tableNameByType map[type]string = map[type]string{
      Person: "person",
}

This statement causes the compiler to yell at me complaining about expected type, found 'type'. I have tried used instead of type, interface{} and struct, with no better results.



Solution 1:[1]

Use reflect.Type as the key:

var tableNameByType map[reflect.Type]string = map[reflect.Type]string{
    reflect.TypeOf(Person{}): "person",
}

You can get the name for a type using:

name := tableNameByType[reflect.TypeOf(Person{})]

... or the name for value v using:

name := tableNameByType[reflect.ValueOf(v).Type()]

You can avoid instantiating the struct value by replacing reflect.TypeOf(Person{}) with reflect.TypeOf((*Person)(nil)).Elem() in the above code.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1