Generic Functions in Go

后端 未结 3 2003
借酒劲吻你
借酒劲吻你 2021-01-18 11:16

I\'m in the process of learning Go and the documentation and interactive lessons say that an empty interface can hold any type, as it requires no a

3条回答
  •  独厮守ぢ
    2021-01-18 12:03

    Not that you can use generic in production as of now (as of 2nd Oct 2020) but for people interested in the upcoming go generics feature, with the latest design draft of go, you can write a generic function Print as below

    package main
    
    import (
        "fmt"
    )
    
    // T can be any type. Compilation will fail if T is not iterable.
    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
    

提交回复
热议问题