Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

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.

Foo = Struct.new(:x, :y)
m = {Foo.new(42, 5) => "Hello"}
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'}

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