SoFunction
Updated on 2025-03-03

Golang Study Notes (III): Control Flow

The control structure is divided into: Condition + Select + Loop

IF

1. Explanation

Copy the codeThe code is as follows:

Conditional expressions have no brackets
Supports an initialization expression (can be a multivariate initialization statement)
The initialization statement defines local variables that can only be used at the block level and cannot be used outside the block.
The opening brace must be on the same line as the conditional statement (must be on the same line as if/else)
go has no ternary operator

If judgment statement conditions do not require brackets
Showing the possibility of declaring a variable in a judgment statement, its scope is only within the logical block and does not work elsewhere
Curly braces must exist and must be on the same line as if/else

2. Syntax

Copy the codeThe code is as follows:

//Basic
if a > 0 {  //No brackets
     dosomething()
} else if a == 0 { //Brams must be used
     doothertings()
} else {
     donothing()
}

//Single-line mode
if a > 0 { a += 100 } else { a -= 100 }

3. Example

Copy the codeThe code is as follows:

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 an initialization statement
if a:=1; a<10 { //Allows to execute a simple statement before the condition, the variable scope defined by this statement is only within the scope of if/else
    return a
}
if a, b := 1,2; a+b == 10 {
}

if x := computedValue(); x > 10 {
} else {
}

4. Results

Copy the codeThe code is as follows:

110
201

Note that in functions with return values, the "final" return statement is not allowed to be placed in the if ... else ... structure, otherwise the compilation fails

Copy the codeThe code is as follows:

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

FOR

For is the "while" of go and only supports for keywords. There are three forms

1. Syntax

Copy the codeThe code is as follows:

for init; condition; post {
//Init does not support commas, can only be assigned in parallel
//condition checks every time the loop starts. It is not recommended to use functions inside. It is recommended to use calculated variables/constants instead.
//The post must be followed by curly braces, and it is called at the end of each round of loop
}

for i:=0; i<10; i++ {
}

-----------------------------

for condition {
    dosomething()
}

i:=1
for i<10 {
}

-----------------------------

for { //Infinite Loop
    dosomething()
}

for {
    a++
    if a > 10 {
        break
    }
}

-----------------------------

2. Explanation

Copy the codeThe code is as follows:

a. Initialization and stepping expressions can make multiple values: parallel assignments must be used
    i, j:=0,len(a)-1; i<j; i,j=i+1,j-1
b. The conditional expression is rechecked every loop

3. Example

Copy the codeThe code is as follows:

package main

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


get:
Copy the codeThe code is as follows:

97
98
99
100

4. Cooperate with range

Use for loops and reserved word range to complete the iterator operation

string, array, slice, map, channel can all be used for iterator operations using range

range returns the sequence number and value. If you don't want it, you can use it_

Copy the codeThe code is as follows:

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

get
Copy the codeThe code is as follows:

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

SWITCH

There is no python

1. Syntax

Support initialization expressions

Copy the codeThe code is as follows:

switch a:=5; a { //Default break, after the match is successful, other cases will not be automatically executed downward, but the entire switch will jump out.
case 0:            //Ordinary
        println(a)
case 1, 2:      // Multiple branches, comma separated
        println(a)
case 100:         //Do nothing
    case 5:
        println(a)
Fallthrough   //Enter into the case behind for processing, rather than jumping out of the block
    default:
println(a) //Default
}
Note that break is not required to explicitly exit a case, and it will be automatically terminated once the conditions meet, unless fallthough is used

--------------

Can be without expressions
switch sExpr {
case expr1: //sExpr and expr1 must have the same type and are not limited to constants or certificates. Any type or expression can be used.
            ...
}

switch {
    case 0 <= Num && Num <= 3:
        ("3")
}

Several forms:

Copy the codeThe code is as follows:

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. Replace if...else if...else...

Do not specify a switch condition expression (no conditional expression, in case statement), or directly true

Copy the codeThe code is as follows:

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

goto break continue

All can be used with tags (tags are case sensitive, if not declared, they will lead to compilation errors)

break/continue can be used to match tags for multiple loops
goto is to adjust the execution position, which is not the same as the other two execution results.

Supports goto jump inside function

Please make good use of it

Must jump to the tag defined in the current function, the tag name is case sensitive

Copy the codeThe code is as follows:

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

Enter the next loop

Terminate the loop

Copy the codeThe code is as follows:

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

Example
Copy the codeThe code is as follows:

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
    }
}

result:

Copy the codeThe code is as follows:

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