进来看几个 Go 的 syntax 代码段吧

2019-05-23 19:07:06 +08:00
 Weixiao0725
  1. 感觉是 go 的一个 bug 啊,网上解释说是因为 switch 之后的打括号放在下一行,所以 go 编译器默认在 switch f()之后加了一个分号。下面的 case 用的是系统默认的 switch 值 true 所以输出 true。但是如果不写 switch 那一行,编译器就直接报错了,说明 switch 和下面的 case 是分不开的啊。
  2. 对于类型 *[]int 和 *[3]int,可以对后者 range 操作,但是前者报编译器错误
  3. 对于第三个就不理解了,请哪位大佬出来解释下。

测试代码: https://play.golang.org/p/7D3nEYF3UFX

	// #1
	f := func() bool { return false }
	switch f()
	{
		case true:
			println("true")
		case false:
			println("false")
	}

	// #2
	arr := [3]int{1,2,3}
	arrPtrOfLen := &arr
	for i := range arrPtrOfLen { println(i) }

	arr2 := []int{1,2,3}
	arrPtrOfVar := &arr2
	for j := range arrPtrOfVar { println(j) } 
	//// arrPtrOfVar compile error: cannot range over data (type *[]int)

	// #3
	for k := range (*[3]int) (nil) {
		println(k)
	}
2312 次点击
所在节点    Go 编程语言
3 条回复
zzn
2019-05-23 23:28:21 +08:00
这些标准里都写的清清楚楚吧
1.
> A missing switch expression is equivalent to the boolean value true.
https://golang.org/ref/spec#Switch_statements

2.
> The expression on the right in the "range" clause is called the range expression, which may be an array, pointer to an array, slice, string, map, or channel permitting receive operations.
https://golang.org/ref/spec#RangeClause

3. 就在 RangeClause 的例子里
liulaomo
2019-05-24 06:55:04 +08:00
Weixiao0725
2019-05-24 08:36:08 +08:00
@zzn @liulaomo 感谢两位解答,谢谢~

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

https://www.v2ex.com/t/567064

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

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

© 2021 V2EX