Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
Select your favorite languages :
  • Or search :

Idiom #282 Use a custom type as map key

Declare a type Foo, and create a new map with Foo as key type.

Mention the conditions on Foo required to make it a possible map key type.

class Foo{};
Map<Foo, int> m = {};
type Foo struct {
	name string
	x, y int
}

m := make(map[Foo]string)
class Foo:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __hash__(self):
        return hash((Foo, self.x, self.y))
    def __eq__(self, other):
        return (self.x, self.y) == (other.x, other.y)

foo = Foo(1, 2)
m = {foo: 'hello'}
Foo = Struct.new(:x, :y)
m = {Foo.new(42, 5) => "Hello"}

New implementation...
< >
programming-idioms.org