Home >Backend Development >Golang >How Do Generics Enable True Generic Functions in Go?

How Do Generics Enable True Generic Functions in Go?

DDD
DDDOriginal
2024-12-18 15:08:13405browse

How Do Generics Enable True Generic Functions in Go?

Generic Functions in Go

Interface types in Go can hold any type without requiring any implemented methods, creating the impression that they serve as a form of generic functions. However, this is not the case. True generic functions, where the type is unknown at compile-time, were not supported in Go before version 1.18.

In Go 1.18, generics were introduced, enabling the creation of generic functions. A generic function can be defined using the func keyword followed by type parameters enclosed in square brackets. The type parameters specify the types accepted by the generic function. For example:

func Print[T any](s []T) {
    for _, v := range s {
        fmt.Print(v)
    }
}

In this example, T is a type parameter that can represent any type. The function Print accepts a slice of type []T and prints the elements of the slice.

To use the generic function, you can pass a slice of the desired type as an argument:

// Passing a list of strings
Print([]string{"Hello, ", "world\n"})

// Passing a list of integers
Print([]int{1, 2})

The output of the program will be:

Hello, world
12

Generic functions provide a concise and safe way to write code that can operate on different types without sacrificing type safety.

The above is the detailed content of How Do Generics Enable True Generic Functions 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