(3) control flow

  • 2020-05-27 05:50:47
  • OfStack

The control structure is divided into: condition + selection + loop

IF

1.


The conditional expression has no parentheses
support 1 (can be a multivariate initialization statement)
Initialization statements are defined only in block Local variables used in the level, cannot be used in block Used outside
The open curly brace must be the same as the conditional statement 1 line ( Must be connected to if/else In the same 1 line )
go There is no 3 Ternary operator if Parentheses are not required to determine statement conditions
Show off permission statements in judgment statements 1 A variable whose scope is only within the logical block and does not apply elsewhere
Curly braces 1 There must be, and must be with if/else In the same 1 line

2. Grammar


// basic
if a > 0 {  // Without parentheses
     dosomething()
} else if a == 0 { // You have to use curly braces
     doothertings()
} else {
     donothing()
} // Single mode
if a > 0 { a += 100 } else { a -= 100 }

Example 3.


package main func main(){
    a := 10     if a > 0 {
        a += 100
    } else if a == 0 {
        a = 0
    } else {
        a -= 100
    }
    println(a)     b := 101
    if b > 0 { b += 100 } else { b -= 100 }
    println(b)
} // support 1 Two initialization statements
if a:=1; a<10 { // Allows execution before conditions 1 The variable scope defined by this statement is only in if/else Within the scope of
    return a
}
if a, b := 1,2; a+b == 10 {
} if x := computedValue(); x > 10 {
} else {
}

Results 4.


110
201

Note that in functions with return values, it is not allowed to put the "final" return statement into if... else... Structure, otherwise the compilation fails


func example(x int) int {
    if x == 0 {
        return 5
    } else {
        return x
    }
}

FOR

for is the "while" of go and only supports the for keyword. It comes in three forms

1. Grammar


for init; condition; post {
    //init Commas are not supported and can only be assigned in parallel
    //condition Check at the beginning of each loop. It is not recommended to use functions inside. It is recommended to use calculated variables / Constants instead of
    //post It must be followed by curly braces , Called at the end of each cycle
} for i:=0; i<10; i++ {
} ----------------------------- for condition {
    dosomething()
} i:=1
for i<10 {
} ----------------------------- for { // An infinite loop
    dosomething()
} for {
    a++
    if a > 10 {
        break
    }
} -----------------------------

2. Show


a. Initialization and stepping expressions enable multiple values: parallel assignments must be used
    i, j:=0,len(a)-1; i<j; i,j=i+1,j-1
b. Each loop rechecks the conditional expression

Example 3.


package main func main(){
    ss := "abcd"
    for i:=0; i<len(ss); i++ {
        println(ss[i])
    }
}

Get:

97
98
99
100

4. Cooperate with range

The for loop and the reserved word range1 are used to complete the iterator iterator operation

string, array, slice, map, channel can all use range for iterator operations

range returns the sequence number and value, or if you don't want it, you can use _


  for i, c := range "abc" {
      fmt.Printf("s[%d] = %c\n", i, c)
  }

get

  s[0] = a
  s[1] = b
  s[2] = c

SWITCH

It's not in python

1. Grammar

Initialization expressions are supported


switch a:=5; a { // The default break , the other will not be automatically executed down after the match is successful case, I'm going to jump out of the whole thing switch
    case 0:         // ordinary
        println(a)
    case 1, 2:      // Multiple branches, separated by commas
        println(a)
    case 100:       // Do nothing
    case 5:
        println(a)
        fallthrough   // Into the back case Deal with it, not jump out of it block
    default:
        println(a)    // The default
}
Notice, no break To explicitly exit 1 a case . 1 When the conditions are met, automatic termination , Unless you use fallthough -------------- You can do it without an expression
switch sExpr {
        case expr1: //sExpr and expr1 Must type 1 to , Not limited to constants or certificates, you can use any type or expression
            ...
} switch {
    case 0 <= Num && Num <= 3:
        fmt.Printf("3")
}

Several forms:


a := 1
switch a {
    case 0:
        ...
} a := 1
switch {
    case a>=0:
        ....
    case a>1:
        ....
} switch a:=1; {
    case a>=0:
        ...
    case a>1:
        ...
}

2. Alternative if... else if... else...

Do not specify switch conditional expressions (no conditional expressions, as in case statements), or simply true


  a := 5
  switch {     // Two sentences can be merged into bits switch a:=5; {
      case a > 1:
          println("a")
      case a > 2:
          println("b")
      default:
          println("c")
  }
 

goto break continue

All can be used with the tag (the tag is case sensitive, if it is not used, it will cause a compilation error)

break/continue can be used with tags for multiple loops
goto is to adjust the execution location, which is different from the other two

1.goto

Support for goto jumps inside functions

Please make good use of

You must jump to the tag defined within the current function. The tag name is case sensitive


func myFunc() {
    i := 0
Here:
    println(i)
    i++
    goto Here
}

2.continue

Enter the next loop

3.break

Terminate the loop


for index := 10; index > 0; index -- {
    if index == 5 {
        break //continue
    }
}

The sample

package main
func main(){
    a := 1
    LABEL1:
        println("inc a=", a)
        a += 1     LABEL2:
        //println("here")     for ; a < 6; {
        println(a)
        if a == 3 {
            a += 1
            continue LABEL2
        }
        if a == 5 {
            break
        }
        goto LABEL1
    }
}

Results:


inc a= 1
2
inc a= 2
3
4
inc a= 4
5


Related articles: