Home >Backend Development >Golang >How Can Recursive Type Constraints Be Achieved in Go Generics Using Interfaces?

How Can Recursive Type Constraints Be Achieved in Go Generics Using Interfaces?

Linda Hamilton
Linda HamiltonOriginal
2024-12-26 15:22:10112browse

How Can Recursive Type Constraints Be Achieved in Go Generics Using Interfaces?

Recursive Type Constraints with Predefined Types

In Go generics, specifying a type constraint on a generic type using an interface is possible. However, it can be challenging to enforce the implementation of a method with an argument of the generic type.

To achieve recursive type constraints in Go generics, we can define an interface with a method that takes the generic type as an argument:

type Lesser[T any] interface {
    Less(T) bool
}

We can then create a function that takes two arguments of type Lesser[T] and returns a boolean:

func IsLess[T Lesser[T]](x, y T) bool {
    return x.Less(y)
}

Now, custom types that implement the Lesser[T] interface can be used in the function:

type Apple int

func (a Apple) Less(other Apple) bool {
    return a < other
}

type Orange int

func (o Orange) Less(other Orange) bool {
    return o < other
}

func main() {
    fmt.Println(IsLess(Apple(10), Apple(20)))   // true
    fmt.Println(IsLess(Orange(30), Orange(15))) // false
}

The Lesser[T] constraint ensures that the types provided to the IsLess function implement a Less method that takes an argument of the same type. This allows for recursive type constraints without the use of type literals.

The above is the detailed content of How Can Recursive Type Constraints Be Achieved in Go Generics Using Interfaces?. 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