Can Go Generics' `comparable` Constraint Be Relaxed for Map Keys?
Go generics: type constraint for map keys?
In Go 1.18 and earlier, the predeclared comparable constraint is required for types that are used as map keys. This constraint ensures that the type supports the == and != operators and does not panic when these operators are used.
However, this constraint is not always appropriate for types that can be used as map keys. For example, the following code defines a generic linked list:
type List[X any] interface { isList() } type Cons[X any] struct { Data X Next List[X] } func (Cons[X]) isList() {} type Nil[X any] struct{} func (Nil[X]) isList() {}
This code defines a List interface that is implemented by two types: Cons and Nil. The Cons type represents a non-empty list, while the Nil type represents an empty list.
The following code uses the List interface to create a map of lists to strings:
type List[X any] interface { isList() } func main() { x := Cons[int]{5, Nil[int]{}} m := map[List[int]]string{} m[x] = "Hi" // succeeds fmt.Println(m[x]) // prints "Hi" }
This code will compile and run successfully. However, if we try to use a method on the type Cons, we will get a compiler error:
type List[X any] interface { isList() } func main() { x := Cons[int]{5, Nil[int]{}} fmt.Println(id(x)) // error: Cons[int] does not implement comparable }
The error message indicates that the type Cons[int] does not implement the comparable constraint. This is because the Cons type has a field of type List[int], and the List[int] interface does not implement the comparable constraint.
One possible solution to this problem is to use a weaker type constraint. For example, we could use the following constraint:
type List[X any] interface { isList() Comparable() bool }
This constraint would allow us to use the Cons type as a map key, even though it does not implement the comparable constraint.
Go 1.20 (February 2023)
The comparable constraint is the correct catch-all constraint for map keys. All types that are comparable as per the Go spec, even if the comparison may panic at run time, can satisfy the comparable constraint. Your code will compile as expected in 1.20.
This finally fixes the inconsistency in previous Go version about spec-comparable types vs comparable types.
The above is the detailed content of Can Go Generics' `comparable` Constraint Be Relaxed for Map Keys?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.
