Home  >  Article  >  Backend Development  >  Golang generic function application

Golang generic function application

WBOY
WBOYOriginal
2024-04-29 13:45:01703browse

Go 1.18 introduces generic functions, supports type parameterization, and enhances code reusability. The syntax of a generic function is func function name [type parameter] (input parameter type parameter) type parameter, and type parameterized types can be used as input and return types. For example, Min[T number] (a, b T) T, where T must be of numeric type, a and b are input parameters of type T, and the smaller number is returned. Generic functions greatly improve the reusability of code, allowing you to write general code that is suitable for various types.

Golang generic function application

Function Application of Generics in Go

Generics introduced in Go 1.18 and later allow functions to accept and return Type parameterized types. This greatly enhances code reusability and flexibility.

Syntax

The syntax of a generic function is as follows:

func myFunc[T any](input T) T {
    // ...
}

Among them:

  • myFunc is the function name.
  • T any is a type parameter. It can be of any type, including custom types.
  • input is an input parameter with a type parameterized type.
  • T is the return type with a type parameterized type.

Practical Case

Suppose we want to create a function to calculate the minimum of two numbers. Generic functions allow us to represent these two numbers with any number type without having to create multiple functions with specific type signatures.

We can write the following generic function:

func Min[T number](a, b T) T {
    if a < b {
        return a
    }
    return b
}

Where:

  • T number means that the type parameter T must be of numeric type (for example int, float64).
  • a and b are input parameters of type T.
  • if-else statement compares two numbers and returns the smaller number.

We can use this function to calculate the minimum value of different types of numbers:

var a int8 = 10
var b int16 = 20
min := Min(a, b)  // 类型推断为 int16
fmt.Println(min)  // 输出:10

Conclusion

Go generics accept by allowing functions and return typed types, greatly improving code reusability and flexibility. By using generic functions, we can write generic code that works across a variety of types.

The above is the detailed content of Golang generic function application. 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