I have a type that can be used as a map key, but I want to prevent this from occurring. I assumed that if the type contained a private member it wouldn't be possible from other packages, but this appears to work anyway. What's the best way to make the type unusable as a map key?
type MyType struct {
A *A
b b
preventUseAsKey ?
}
Your type should not be comparable in order to be unfit as a map key.
See Key Type:
So if your type is a slice, map or function, you should get what you need.
It could be an "alias" (defining a new named type):
That alias would not be used as a map key.
Update 2017: Brad Fitzpatrick give this tip (adding a slice in your
struct
) to make sure your typestruct
is not comparable: See play.golang.org:T
cannot be used as amp key now!I don't see any benefit of disallowing a type being used as a key. It is just an option which may or may not be used, the type will not be any better or smaller or faster just because you forbid to use it as a map key.
But if you want to do it: Spec: Map types:
So if you can violate the terms of the comparison operators, you implicitly get what you want. You have a
struct
, terms for thestruct
types:So
struct
values are only comparable (and thus can only be used as keys in maps) if all their fields are comparable. Simply add a field whose type is not comparable.So for example add a field whose type is a slice, and you're done:
Attempting to use the above
MyType
as a key:You get a compile-time error:
Note:
I wrote about not having any benefit of forbidding the type being a key. It's more than that: from now on you won't be able to use comparison operators on values of your type anymore (because of the extra, non-comparable field), so e.g. you lose the option to compare those values:
Compile-time error:
Note that with a little trick you could still preserve the comparable nature of your type, e.g. by not exporting your type but a wrapper type which embeds the original one; and add the extra, non-comparable type to the wrapper type, e.g.:
This way your
myType
can remain comparable but still prevent the exported, wrapperMyType
type to be used as key type.