Generics were introduced in Go 1.18 to create type-independent code. Generics use square brackets [] to define type parameters, such as func Sort[T any](arr []T). The Go compiler can infer type parameters like func Swap[T](x, y T). Generics can be used to build data structures, such as a binary search tree type Node[T any] struct { … }, and impose type constraints, such as type Node[T comparable] struct { … }. Go generics increase code flexibility without creating new types.
In Go 1.18, the Go language introduces a highly anticipated feature: Generics. Generics allow you to create data structures and algorithms that are independent of specific types, making your code more reusable and flexible.
Generics are defined using square brackets []
, which contain any number of type parameters:
func Sort[T any](arr []T)
In the above example , T
is a type parameter, which means it can be an item of any type.
The function's generic type parameters can be omitted if they can be inferred from the context:
func Swap[T](x, y T)
This function can take two arguments of any type Used together, the Go compiler will infer that T
should be of type x
and y
.
Let us create a generic version of the binary search tree:
type Node[T any] struct { Value T Left *Node[T] Right *Node[T] } func Insert[T comparable](n *Node[T], value T) *Node[T] { // ... } func Search[T comparable](n *Node[T], value T) *Node[T] { // ... }
This binary search tree allows us to store and search any Elements of comparable types.
Sometimes you need to impose constraints on type parameters. For example, to ensure that comparing two values in a binary search tree is valid, we can require that T
implements the comparable
interface:
type Node[T comparable] struct { // ... }
Go generics bring powerful new features to the Go language. Understanding how to define and use generics is key to making your code more flexible and reusable.
The above is the detailed content of The definition and application of Golang generics. For more information, please follow other related articles on the PHP Chinese website!