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
Release: 2024-12-29 04:36:10
Original
370 people have browsed it

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)
}
Copy after login

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"
Copy after login

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})
}
Copy after login

Output:

Hello, world
12
Copy after login

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 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template