Home > Backend Development > Golang > What's the Difference Between `comparable` and `Ordered` Constraints in Go Generics for Type Comparisons?

What's the Difference Between `comparable` and `Ordered` Constraints in Go Generics for Type Comparisons?

Barbara Streisand
Release: 2024-12-10 14:36:11
Original
793 people have browsed it

What's the Difference Between `comparable` and `Ordered` Constraints in Go Generics for Type Comparisons?

Comparable Constraints vs. Ordered Operators in Go Generics

In Go generics, the comparable constraint restricts types that support equality operators (== and !=), while ordered operators (<, >, <=, and >=) require the Ordered constraint.

Consider the following code:

import "fmt"

type numbers interface {
    int | int8 | int16 | int32 | int64 | float32 | float64
}

func getBiggerNumber[T numbers](t1, t2 T) T {
    if t1 > t2 {
        return t1
    }
    return t2
}

func getBiggerNumberWithComparable[T comparable](t1, t2 T) T {
    if t1 > t2 { // Compile error
        return t1
    }
    return t2
}

func main() {
    fmt.Println(getBiggerNumber(2.5, -4.0))
    fmt.Println(getBiggerNumberWithComparable(2.5, -4.0))
}
Copy after login

The error in getBiggerNumberWithComparable arises because comparable does not guarantee order comparison. It includes map key types that do not support ordering.

Solution for Go 1.18 to 1.20

Prior to Go 1.21, use constraints.Ordered:

import (
    "fmt"
    "golang.org/x/exp/constraints"
)

func getBiggerNumberWithOrdered[T constraints.Ordered](t1, t2 T) T {
    if t1 > t2 {
        return t1
    }
    return t2
}
Copy after login

Solution for Go 1.21

In Go 1.21 and later, use cmp.Ordered:

import (
    "fmt"

    "golang.org/x/exp/constraints"
    "github.com/google/go-cmp/cmp"
)

func getBiggerNumberWithOrdered[T cmp.Ordered](t1, t2 T) T {
    if cmp.Less(t1, t2) {
        return t2
    }
    return t1
}
Copy after login

The above is the detailed content of What's the Difference Between `comparable` and `Ordered` Constraints in Go Generics for Type Comparisons?. 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