Logo

Programming-Idioms

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.
New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

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

m := make(map[Foo]string)
local map={[Foo]=true}
use Object::Pad;
class Foo {
    has $x :param = 0;
}
 
my $p = Foo->new(x => 5);

my %map;

$map{$p} = 'some data';
package Foo {    
    sub new { 
        my $class = shift; 
        return bless { @_ }, $class 
    }    
};
 
my $p = Foo->new(x => 5);

my %map;

$map{$p} = 'some data';
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"}