Home > Backend Development > Golang > Understand the core concepts of Golang generics

Understand the core concepts of Golang generics

WBOY
Release: 2024-04-03 12:18:01
Original
552 people have browsed it

Go generics allow the creation of reusable types and functions without modifying the code itself. It includes: Generic types: Use type parameters, allowing parameter types to be specified when creating the type (e.g. []T, map[K]V). Generic functions: When using type parameters, an explicit type parameter list must be specified. Constraints: Restrict the usage of generic types. Use the keywords any, comparable, and type interfaces to specify type restrictions on type parameters. With these concepts, it is possible to create more robust and general-purpose code, such as generic sorting algorithms.

Understand the core concepts of Golang generics

Understand the core concepts of Golang generics

Preface
Generics are in Go 1.18 An important new feature introduced that allows us to create reusable types and functions without modifying the code itself. This tutorial will introduce the core concepts of generics in Go and demonstrate their usage through practical examples.

Generic types
Generic types parameterize types, allowing us to specify parameter types when creating the type. This can be achieved by using a type creator such as []T or map[K]V, where T and V are respectively Value types and key types.

// 定义一个泛型 slice 类型
type MySlice[T any] []T

// 创建一个 MySlice[int] 实例
s := MySlice[int]{1, 2, 3}
Copy after login

Generic functions
Generic functions can also take type parameters, but they must also specify an explicit type parameter list.

// 定义一个将切片元素加倍的泛型函数
func Double[T ~int | ~float64](s []T) []T {
  for i, v := range s {
    s[i] = v * 2
  }
  return s
}
Copy after login

Constraints
Constraints allow us to restrict the usage of generic types by specifying type restrictions on type parameters. Constraints are implemented using the keywords any, comparable and the type interface.

// 定义一个泛型 map 类型,键值为可比较类型
type MyMap[K comparable, V any] map[K]V

// 定义一个泛型函数来查找切片中的最大值
func Max[T any](s []T) T where T: ~int | ~float64 {
  max := s[0]
  for _, v := range s {
    if v > max {
      max = v
    }
  }
  return max
}
Copy after login

Practical case
Let us build a simple sorting algorithm using generics:

// 定义泛型交换函数
func Swap[T any](s []T, i, j int) {
  temp := s[i]
  s[i] = s[j]
  s[j] = temp
}

// 定义泛型排序函数
func Sort[T any](s []T) where T: ~int | ~float64 | ~string {
  for i := 0; i < len(s); i++ {
    for j := i + 1; j < len(s); j++ {
      if s[j] < s[i] {
        Swap(s, i, j)
      }
    }
  }
}
Copy after login

Conclusion

Generics in Go provide powerful tools for code reuse and flexibility. By understanding type parameterization, constraints, and practical examples, developers can take advantage of this feature to create more robust and versatile code.

The above is the detailed content of Understand the core concepts of 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