Yes, that is a one way of doing it. I found another way. The compiler
does not allow to put anything in the map[interface{}] interface,
but I could create the following wrapper, which allows to put anything
in the map.
package main
import (
"fmt";
)
type GenericMap struct {
m map[interface{}] interface{};
}
func NewGenericMap() (*GenericMap) {
m := make(map[interface{}] interface{});
return &GenericMap{ m };
}
func (g *GenericMap) put(key interface{}, value interface{}) {
g.m[key] = value;
}
func (g *GenericMap) get(key interface{}) (value interface{}) {
return g.m[key];
}
func (g *GenericMap) contains(key interface{}) bool {
_,present := g.m[key];
return present;
}
func (g *GenericMap) String() string {
return fmt.Sprintf("%s", g.m);
}
type Struct struct {
k int;
}
func main() {
gm := NewGenericMap();
gm.put(1, 2);
gm.put("A", "B");
s := Struct{3};
gm.put(&s, Struct{4});
fmt.Printf("%s\n", gm.get(1));
fmt.Printf("%s\n", gm.get("A"));
fmt.Printf("%s\n", gm.get(&s));
fmt.Printf("%t\n", gm.contains("C"));
fmt.Printf("%s\n", gm);
m := make(map[interface{}] interface{});
m[1] = 2; //invalid map index 1 - need type interface { }
m["A"] = "B"; //invalid map index "A" - need type interface { }
m[&s] = s; //invalid map index &s - need type interface { }
}
On Nov 28, 4:16 pm, inspector_jouve <
kaushan...@gmail.com> wrote:
> You can have all your heterogeneous types implement same interface
> with method key(), which returns either string or some kind of int,
> and use it as key, e.g.
> m:=make(map[string] Foo);
> ...
> m[myobj.key()]=foo