Home >Backend Development >Golang >Are Go's Empty Interfaces or Go 1.18 Generics the True Implementation of Generic Functions?

Are Go's Empty Interfaces or Go 1.18 Generics the True Implementation of Generic Functions?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-29 04:36:10318browse

Are Go's Empty Interfaces or Go 1.18 Generics the True Implementation of Generic Functions?

Generic Functions in Go: A Comprehensive Guide

While exploring Go, you may encounter the concept of an empty interface. It's a powerful tool that can hold any type, requiring no additional methods.

Consider this example:

func describe(i interface{}) {
    fmt.Printf("Type: %T | Value: %v\n", i, i)
}

When you pass different types to describe, it prints out the type and value:

"Type: int | Value: 5" // for i := 5
"Type: string | Value: test" // for i := "test"

So, is this Go's way of implementing generic functions? Not quite. Starting with Go 1.18, you can now write true generic functions. Here's an example:

package main

import (
    "fmt"
)

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

func main() {
    // Passing list of string works
    Print([]string{"Hello, ", "world\n"})

    // You can pass a list of int to the same function as well
    Print([]int{1, 2})
}

Output:

Hello, world
12

This generic function Print can handle slices of any type, offering a more versatile and type-safe approach to generic programming.

The above is the detailed content of Are Go's Empty Interfaces or Go 1.18 Generics the True Implementation of Generic Functions?. 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