Home >Backend Development >Golang >How to Write a Generic Function for Numerical Types in Go?

How to Write a Generic Function for Numerical Types in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-18 00:00:14592browse

How to Write a Generic Function for Numerical Types in Go?

How to Create a Generic Function for Numerical Types in Go

As JavaScript and TypeScript users, you may wonder about handling numerical types in Go while working with int and float. This article explores the best ways to create a generic function that can accept any numerical argument.

Generic Functions in Go 1.18 and Above

With the introduction of type parameters in Go 1.18, you can now define functions parameterized in type T. Utilizing the interface constraint, you can restrict T to numeric types.

func add[T Number](a, b T) T {
    return a + b
}

Here, the constraint Number is defined using the golang.org/x/exp/constraints package:

type Number interface {
    constraints.Integer | constraints.Float
}

This constraint ensures that T must be a type that satisfies either constraints.Integer or constraints.Float.

Using Generic Functions

This generic add function can handle arguments of any numeric type. However, it's important to note that both arguments must be of the same type. For instance:

fmt.Println(add(1, 2))     // 3
fmt.Println(add(a, b))     // 3
fmt.Println(add(1.5, 3.2)) // 4.7

Attempting to mix types, such as add(2.5, 2), will result in a compilation error.

Complex Numbers Support

You can extend the Number constraint to include complex types:

type Number interface {
    constraints.Integer | constraints.Float | constraints.Complex
}

Despite being supported by complex types, the arithmetic operators , -, *, and / remain the only supported operators. Modulus % and bitwise operators are not supported for complex types.

The above is the detailed content of How to Write a Generic Function for Numerical Types in Go?. 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