The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
Weixiao0725

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

  •  
  •   Weixiao0725 · May 23, 2019 · 3098 views
    This topic created in 2571 days ago, the information mentioned may be changed or developed.
    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)
    	}
    
    zzn
        1
    zzn  
       May 23, 2019
    这些标准里都写的清清楚楚吧
    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 的例子里
    Weixiao0725
        3
    Weixiao0725  
    OP
       May 24, 2019
    @zzn @liulaomo 感谢两位解答,谢谢~
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1232 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 17:46 · PVG 01:46 · LAX 10:46 · JFK 13:46
    ♥ Do have faith in what you're doing.