Golang 泛型:[type T],为啥要用中括号呢。。。

2020 年 8 月 4 日
 viktor123

传送门: https://blog.golang.org/generics-next-step

官方示例:

package main

import (
	"fmt"
)

// The playground now supports parentheses or square brackets (only one at
// a time) for generic type and function declarations and instantiations.
// By default, parentheses are expected. To switch to square brackets,
// the first generic declaration in the source must use square brackets.

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

func main() {
	Print([]string{"Hello, ", "playground\n"})
}

High Level Overview:

4603 次点击
所在节点    程序员
22 条回复
cmdOptionKana
2020 年 8 月 4 日
盲猜因为初始方案是小括号,被说小括号太多。而小于号大于号本质上不是括号,可能会影响编译速度(或语法分析的复杂性),官方好像一开始就讨厌尖括号。所以折中一下就是中括号了。
TypeError
2020 年 8 月 4 日
看起来还好,能和圆括号分清就行
mind3x
2020 年 8 月 4 日
很好,迈出了走向 Scala 的第一步 [并没有]
janxin
2020 年 8 月 4 日
因为不想用<>,因为不少额外有工作量,()有语法歧义
Fitz
2020 年 8 月 4 日
唉, 什么时候改成方括号了, 记得 6 月份的时候不是圆括号吗
so1n
2020 年 8 月 4 日
好像跟 python 不用<>的理由一样
Fitz
2020 年 8 月 4 日
6 月份的帖子还在呢 https://v2ex.com/t/682238#r_9129287
viktor123
2020 年 8 月 4 日
@Fitz thx bro.
aloxaf
2020 年 8 月 4 日
看着比小括号舒服多了……
allenhu
2020 年 8 月 4 日
恕我一眼看不懂
iyear
2020 年 8 月 4 日
比尖尖的舒服多了。。。
zhuangzhuang1988
2020 年 8 月 4 日
Scala 也是[]
<> 是留给 xml 用的
tolerance
2020 年 8 月 4 日
等正式发布再说
someonedeng
2020 年 8 月 5 日
其实看起来还不错
yrj
2020 年 8 月 5 日
我记得上一稿方案是小括号,还是中括号舒服
sunxiansong
2020 年 8 月 5 日
fengjianxinghun
2020 年 8 月 5 日
欢迎,[]()()() 比 ()()()()至少强了一分钱。
lithbitren
2020 年 8 月 5 日
比小括号要更好
fengjianxinghun
2020 年 8 月 5 日
```go

package main

import (
"fmt"
)


// The playground now supports parentheses or square brackets (only one at
// a time) for generic type and function declarations and instantiations.
// By default, parentheses are expected. To switch to square brackets,
// the first generic declaration in the source must use square brackets.


type primitive interface {
type string, int, uint, float32
}

func Print[type T primitive](s []T) {
for _, v := range s {
fmt.Print(v)
}
fmt.Print("\n")
}

func main() {
Print([]string{"Hello, ", "playground"})
Print([]int{1,2,3,4,5})
Print([]float32{1.0})
}


```
Mohanson
2020 年 8 月 5 日
Golang 语法树解析的复杂度是 LR(1), 得益于其 Token 的 parser 是 context free 的. 按照 Go 的性格来说, 它不可能使用 <> , 因为一旦加上这个符号就会出现歧义, 要联系上下文去"猜"这个 Token 的含义, 复杂度会变成 LR(无穷). 括号内的数字和上下文的大小成正比.

编译速度在 Golang 看来是很重要的.

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://study.congcong.us/t/695614

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX