Home >Backend Development >Golang >How to create custom types using Golang generics?

How to create custom types using Golang generics?

WBOY
WBOYOriginal
2024-06-02 10:45:59642browse

如何使用 Golang 泛型创建自定义类型?

Create custom types using Golang generics

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.

Define a custom 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 a8093152e673feb7aba1828c43532094. 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.

Creating Type Instances

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}

Practical Case

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

Note

  • Type parameters must use the any keyword, which indicates that the parameter can be of any type.
  • Type parameters cannot be type aliases or interfaces.
  • Type parameters cannot have type constraints.

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!

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