Can You Prevent a Type from Being Used as a Map Key in Go?

Linda Hamilton
Release: 2024-10-27 09:06:30
Original
970 people have browsed it

 Can You Prevent a Type from Being Used as a Map Key in Go?

Preventing Type Usage as Map Key

Although it is generally beneficial to have a type that can serve as a map key, in some instances, it may be necessary to restrict its use as such. While assuming the presence of a private member in a type would prevent it from being employed as a map key outside the defining package is a common misconception, in reality, it doesn't offer such protection.

Best Approach to Prevent Map Key Usage

The most effective way to prevent a type from being utilized as a map key is to violate the specification for map types, which mandates that key types must enable the definition of comparison operators (== and != ). By incorporating a field within the type whose type is deemed incomparable, such as a slice or function, you can effectively prohibit its use as a map key.

Consider the following example:

type MyType struct {
    S             string
    i             int
    notComparable []int
}
Copy after login

An attempt to use MyType as a map key:

m := map[MyType]int{}
Copy after login

Will result in a compile-time error:

invalid map key type MyType
Copy after login

Consequences of Preventing Map Key Usage

It is important to note that by taking this measure, you will forfeit the ability to compare values of your type using comparison operators. For instance, the following code will no longer function:

p1, p2 := MyType{}, MyType{}
fmt.Println(p1 == p2)
Copy after login

Compile-time error:

invalid operation: p1 == p2 (struct containing []int cannot be compared)
Copy after login

Preserving Comparability

If you wish to preserve the comparability of your type while preventing its use as a map key, you can employ a technique involving embedding and wrapper types. For example:

type myType struct {
    S string
    i int
}

type MyType struct {
    myType
    notComparable []int
}
Copy after login

Through this approach, myType remains comparable, while the exported wrapper type MyType cannot be utilized as a map key.

The above is the detailed content of Can You Prevent a Type from Being Used as a Map Key in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!