Home > Backend Development > Golang > How do you implement comparison functionality for custom types in Go?

How do you implement comparison functionality for custom types in Go?

Susan Sarandon
Release: 2024-11-04 05:53:01
Original
776 people have browsed it

How do you implement comparison functionality for custom types in Go?

Comparable Interface in Go

In Go, there is no built-in interface that requires a type to implement a comparison function. However, you can create your own interface to define a comparable type.

Defining a Comparable Interface

A common approach is to create an interface with the following methods:

type Comparable[T comparable] interface {
    Compare(other T) int
}
Copy after login

Where T is the type that implements the interface and int represents a comparison result (-1, 0, 1).

Implementing the Interface

For a custom type to be considered comparable, it must implement the Comparable interface:

type MyType struct {
    // ...
}

func (t MyType) Compare(other MyType) int {
    // ...
}
Copy after login

Using a Comparable Interface

Once you have defined a Comparable interface, you can use it to check if a type is comparable:

func IsComparable(i interface{}) bool {
    _, ok := i.(Comparable[i])
    return ok
}
Copy after login

You can also use the Less function to compare two comparable values:

func Less(a, b Comparable[T]) bool {
    return a.Compare(b) < 0
}
Copy after login

The above is the detailed content of How do you implement comparison functionality for custom types 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