|
| 1 | +# 如何在 Go 1.17 中使用范型 |
| 2 | + |
| 3 | +我们知道,Go 1.18 预计将在今年末或明年初发布时为 Go 语言带来范型。 |
| 4 | +但对于那些等不及的人, 可以从 [Go Playground](https://go2goplay.golang.org/) 的特定版本在线尝试范型, |
| 5 | +还有一种方法可以让你在本地环境尝试范型,不过有点麻烦, |
| 6 | +需要从 [源码](https://go.googlesource.com/go/+/refs/heads/dev.go2go/README.go2go.md) 编译 Go。 |
| 7 | + |
| 8 | +直到今天 Go 1.17 发布: |
| 9 | + |
| 10 | + |
| 11 | + |
| 12 | +除了一些新特性,还有一个特定的标记参数 `-gcflags=-G=3`,在编译或运行的时候加上它就能使用范型。 |
| 13 | +我第一次在这里看到他,但是除了这个来源,我还发现一些其他的公共消息。 |
| 14 | + |
| 15 | + |
| 16 | + |
| 17 | +总之,我很高兴确认它可以用!然后要说明的是,我是在 go2go playground 运行下面的代码: |
| 18 | + |
| 19 | +```go |
| 20 | +package main |
| 21 | + |
| 22 | +import ( |
| 23 | + "fmt" |
| 24 | +) |
| 25 | + |
| 26 | +// The playground now uses square brackets for type parameters. Otherwise, |
| 27 | +// the syntax of type parameter lists matches the one of regular parameter |
| 28 | +// lists except that all type parameters must have a name, and the type |
| 29 | +// parameter list cannot be empty. The predeclared identifier "any" may be |
| 30 | +// used in the position of a type parameter constraint (and only there); |
| 31 | +// it indicates that there are no constraints. |
| 32 | + |
| 33 | +func Print[T any](s []T) { |
| 34 | + for _, v := range s { |
| 35 | + fmt.Print(v) |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +func main() { |
| 40 | + Print([]string{"Hello, ", "playground\n"}) |
| 41 | +} |
| 42 | +``` |
| 43 | + |
| 44 | +当我尝试用刚刚提到的参数运行的时候,会导致下面的错误: |
| 45 | + |
| 46 | +```bash |
| 47 | +$ go1.17 run -gcflags=-G=3 cmd/generics/main.go |
| 48 | + |
| 49 | +# command-line-arguments |
| 50 | +cmd/generics/main.go:14:6: internal compiler error: Cannot export a generic function (yet): Print |
| 51 | +No problem, lets unexport Printfor now, by renaming it to print. |
| 52 | +``` |
| 53 | + |
| 54 | +现在运行相同的命令绝对可以正确执行! |
| 55 | + |
| 56 | +```go |
| 57 | +$ go1.17 run -gcflags=-G=3 cmd/generics/main.go |
| 58 | + |
| 59 | +Hello, playground |
| 60 | +``` |
| 61 | + |
| 62 | +## 这到底有什么用? |
| 63 | + |
| 64 | +毫无疑问,这肯定是前进的一步。如果你想尝试范型,你必须从源码编译 Go。 |
| 65 | +然而,Go 编译器的实现也只是完成了一半工作,另外一半是工具链的支持。 |
| 66 | +根据我有限的测试,似乎只有 `run` 和 `build` 命令支持了这个参数,其他的命令,比如格式化或测试都没有成功。 |
| 67 | + |
| 68 | +随着 Go 1.18 越来越近,我很期待看到更多工具链的支持。 |
| 69 | + |
| 70 | +--- |
| 71 | +via: https://preslav.me/2021/08/17/how-to-use-generics-in-golang-starting-from-go1-17/ |
| 72 | + |
| 73 | +作者:[Preslav Rachev](https://preslav.me/author/preslav/) |
| 74 | +译者:[h1z3y3](https://www.h1z3y3.me) |
| 75 | +校对:[校对者ID](https://github.com/校对者ID) |
| 76 | + |
| 77 | +本文由 [GCTT](https://github.com/studygolang/GCTT) 原创编译,[Go 中文网](https://studygolang.com/) 荣誉推出 |
0 commit comments