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

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

Susan Sarandon
Susan SarandonOriginal
2024-11-04 05:53:01716browse

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
}

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 {
    // ...
}

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
}

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

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

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!

Statement:
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