Golang 1.18 introduces generics, a way to create typed parameterized code that helps create Highly reusable and maintainable code. It allows us to define types with type placeholders that can be replaced with specific types when creating instances of the type.
To create a custom type, you can use the type
keyword, followed by the type name and type parameters. Type parameters are enclosed in angle brackets <>. For example, we can create a type named Pair
that stores a pair of values of any type:
type Pair[T1, T2 any] struct { first T1 second T2 }
where:
T1
and T2
are type parameters, meaning they can be replaced by any type. struct
defines a structure containing two fields first
and second
. Once a custom type is defined, instances of it can be created by specifying type parameters. For example, to create a Pair
instance to store strings and integers, we can use the following code:
pair := Pair[string, int]{"John", 30}
Generics have many practical applications in Golang . A common case is to create generic functions or methods that can operate on various types. For example, we can create a Swap
function that swaps values on two different types:
func Swap[T1, T2 any](a *T1, b *T2) { temp := *a *a = *b *b = temp }
To use this function, we can pass pointers of two different types as arguments :
a := 5 b := "Hello" Swap(&a, &b) fmt.Println(a, b) // 输出:"Hello" 5
any
keyword, which indicates that the parameter can be of any type. The above is the detailed content of How to create custom types using Golang generics?. For more information, please follow other related articles on the PHP Chinese website!