Mar 5, 2021

[Go] line-break rules

Reference: https://go101.org/article/line-break-rules.html


The formal grammar uses semicolons ";" as terminators in a number of productions. Go programs may omit most of these semicolons using the following two rules:

  1. (ADD ; after token for us) When the input is broken into tokens, a semicolon is automatically inserted into the token stream immediately after a line's final token if that token is
  2. (ADD ; before ')' '}' for us) To allow complex statements to occupy a single line, a semicolon may be omitted before a closing ")" or "}".
  • We can only break a line after the dot, as the following code shows
  • 	anObject.
    		MethodA().
    		MethodB().
    		MethodC()
    
  • Weird but valid code
    
    package main
    
    import "fmt"
    
    func alwaysFalse() bool {return false}
    
    func main() {
    	for
    	i := 0
    	i < 6
    	i++ {
    		// use i ...
    	}
    
    	if x := alwaysFalse()
    	!x {
    		// do something ...
    	}
    
    	switch alwaysFalse()
    	{
    	case true: fmt.Println("true")
    	case false: fmt.Println("false")
    	}
    } 


    the last switch expression equals to
    
    switch alwaysFalse(); true {
    	case true: fmt.Println("true")
    	case false: fmt.Println("false")
    	}
    

    Thus always print 'true'
    The default switch expression of a switch block is a typed value true of the predeclared type bool.

It is a good habit to run 'go fmt' and 'go vet' often for your code.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.