How to create custom types using Golang generics?

WBOY
Release: 2024-06-02 10:45:59
Original
609 people have browsed it

如何使用 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 <>. 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
}
Copy after login

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}
Copy after login

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
}
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!