golang process control summary

Process control in go language

This article video tutorial address: https://www.bilibili.com/vide...

Conditions in go language

Conditional statements are used to judge whether a given condition is satisfied (whether the expression value is true or false) and determine the execution according to the judgment result (true or false). The same is true for conditional statements in go language.

The conditional statements in go language include the following situations

  1. if statement: an if statement consists of a Boolean expression followed by one or more statements.
  2. if...else statement: an optional else statement can be used after the if statement. The expression in the else statement is executed when the Boolean expression is false.
  3. If nested statements: you can embed one or more if or else if statements in an if or else if statement.
  4. Switch statements: switch statements are used to perform different actions based on different conditions.
  5. Select statement: a select statement is similar to a switch statement, but select randomly executes a runnable case. If there is no case to run, it will block until there is a case to run.

Loop statement in go language

The only loop in go language is the for loop, which eliminates the while, do while loops and makes it more concise to use.

  1. for loop.
  2. for range loop.

Process control keywords in go language

  1. break
  2. continue
  3. goto

if statement in golang

if statements in go language are similar to those in other languages. They judge the execution process according to the operation results of a given conditional expression.

go language if statement syntax

if Boolean expression {
   /* Execute when Boolean expression is true */
}

Note: Boolean expressions do not use parentheses in the go language.

go language if statement example demonstration

Judge according to boolean flag

import "fmt"

func test1() {
    var flag = true
    if flag {
        fmt.Println("flag is true")
    }
    fmt.Printf("End of program operation")
}

func main() {
    test1()
}

Program running results

flag is true
 End of program operation

Adult is judged by age

package main

import "fmt"

func test2() {
    var age = 20
    if age > 18 {
        fmt.Println("You're an adult")
    }
    fmt.Printf("End of program operation")
}

func main() {
    test2()
}

Program running results

You're an adult
 End of program operation

The initial variable can be declared in a Boolean expression. Pay attention to its scope

func test3() {
    if age := 20; age > 18 {
        fmt.Println("You're an adult")
    }
    fmt.Printf("End of program operation")
}

func main() {
    // test1()
    // test2()
    test3()
}

Program running results

You're an adult
 End of program operation

Note: 0 or non-0 cannot be used to indicate true or false

func test4() {
    var i = 1
    if i { // Compilation failed
        fmt.Println("here")
    }
    fmt.Printf("End of program operation")
}

Tips for if statement in go language:

  1. You do not need parentheses to enclose conditions
  2. Braces {} must exist, even if there is only one line of statement
  3. The left parenthesis must be on the same line as if or else
  4. After if and before conditional statements, you can add variable initialization statements, using; Separate

if else statement in golang

if else statements in go language can choose one from the other according to given conditions.

if else statement syntax of go language

if Boolean expression {
   /* Execute when Boolean expression is true */
} else {
  /* Executes when the Boolean expression is false */
}

go language if else statement instance

Compare the size of two numbers

package main

import "fmt"

func f1() {
    a := 1
    b := 2
    if a > b {
        fmt.Printf("\"a>b\": %v\n", "a>b")
    } else {
        fmt.Printf("\"a<=b\": %v\n", "a<b")
    }
}

func main() {
    f1()
}

Judge whether a number is odd or even

func f2() {
    var s int
    fmt.Println("Enter a number:")
    fmt.Scan(&s)

    if s%2 == 0 {
        fmt.Print("s It's an even number\n")
    } else {
        fmt.Print("s Not even\n")
    }
    fmt.Print("s The values are:", s)
}

Judging whether a person is an adult

func f3() {
    age := 20
    if age >= 18 {
        fmt.Println("You're an adult")
    } else {
        fmt.Println("You're under age")
    }
}

Special writing method, add execution statement before if

func f4() {
    if age := 20; age >= 18 {
        fmt.Println("You're an adult")
    } else {
        fmt.Println("You're under age")
    }
}

Tips for if statement in go language:

  1. You do not need parentheses to enclose conditions
  2. Braces {} must exist, even if there is only one line of statement
  3. The left parenthesis must be on the same line as if or else
  4. After if and before conditional statements, you can add variable initialization statements, using; Separate

If else statement in golang

if statements in go language can be used for multiple nesting and multiple judgment.

If else syntax in go language

if Boolean expression 1 {
    // do something
} else if Boolean expression 2 {
    // do something else
}else {
    // catch-all or default
}

Examples of if else syntax in go language

Judge the grade according to the score

func f5() {
    score := 80
    if score >= 60 && score <= 70 {
        fmt.Println("C")
    } else if score > 70 && score <= 90 {
        fmt.Println("B")
    } else {
        fmt.Println("A")
    }
}

Program running results

B

It can also be written like this

func f5() {
    if score := 80; score >= 60 && score <= 70 {
        fmt.Println("C")
    } else if score > 70 && score <= 90 {
        fmt.Println("B")
    } else {
        fmt.Println("A")
    }
}

Enter the first letter of the day of the week to judge the day of the week. If the first letter is the same, continue to judge the second letter

func f6() {
    //  Monday Tuesday Wednesday Thursday Friday Saturday Sunday
    var c string
    fmt.Println("Enter a character:")
    fmt.Scan(&c)

    if c == "S" {
        fmt.Println("Enter the second character:")
        fmt.Scan(&c)
        if c == "a" {
            fmt.Println("Saturday")
        } else if c == "u" {
            fmt.Println("Sunday")
        } else {
            fmt.Println("Input error")
        }
    } else if c == "F" {
        fmt.Println("Friday")
    } else if c == "M" {
        fmt.Println("Monday")
    } else if c == "T" {
        fmt.Println("Enter the second character:")
        fmt.Scan(&c)
        if c == "u" {
            fmt.Println("Tuesday")
        } else if c == "h" {
            fmt.Println("Thursday")
        } else {
            fmt.Println("Input error")
        }
    } else if c == "W" {
        fmt.Println("Wednesday")
    } else {
        fmt.Println("Input error")
    }
}

Nested if statements in golang

if statements in go language can be nested at multiple levels for judgment.

go language if nested syntax

if Boolean expression 1 {
   /* Executes when Boolean expression 1 is true */
   if Boolean expression 2 {
      /* Executes when Boolean expression 2 is true */
   }
}

go language if nested instance

Judge the size of three numbers

package main

import "fmt"

// a>b a>c a
// b>a b>c b else c

func f1() {
    a := 100
    b := 200
    c := 3
    if a > b {
        if a > c {
            fmt.Println("a maximum")
        }
    } else {
        if b > c {
            fmt.Println("b maximum")
        } else {
            fmt.Println("c maximum")
        }
    }
}

func main() {
    f1()
}

Judge whether boys or girls, and whether they are adults

func f2() {
    // Judge male and female students and age
    gender := "girl student"
    age := 16
    if gender == "schoolboy" {
        fmt.Println("schoolboy")
        if age > 18 {
            fmt.Println("adult")
        } else {
            fmt.Println("under age")
        }
    } else {
        fmt.Println("girl student")
        if age > 18 {
            fmt.Println("adult")
        } else {
            fmt.Println("under age")
        }
    }
}

golang switch statement

The switch statement in go language can easily judge the situation of multiple values.

Syntax of switch statement in go language

switch var1 {
    case val1:
        ...
    case val2:
        ...
    default:
        ...
}

An example of switch statement in go language

Judge achievement

func f() {
    grade := "A"
    switch grade {
    case "A":
        fmt.Println("excellent")
    case "B":
        fmt.Println("good")
    default:
        fmt.Println("commonly")
    }
}

Operation results

excellent

Multi condition matching

switch statements in go language can match multiple conditions at the same time, separated by commas, and one of them can be matched successfully.

func f() {
    day := 3
    switch day {
    case 1, 2, 3, 4, 5:
        fmt.Println("weekdays")
    case 6, 7:
        fmt.Println("Rest Day")
    }
}

Operation results

weekdays

case can be a conditional expression

func f() {
    score := 90
    switch {
    case score >= 90:
        fmt.Println("Enjoy the holidays")
    case score < 90 && score >= 80:
        fmt.Println("Study hard!")
    default:
        fmt.Println("Study hard!")
    }
}

Operation results

Enjoy the holidays

fallthrough can execute the next case that satisfies the condition

func f3() {
    a := 100
    switch a {
    case 100:
        fmt.Println("100")
        fallthrough
    case 200:
        fmt.Println("200")
    case 300:
        fmt.Println("300")
    default:
        fmt.Println("other")
    }
}

Operation results

100
200

Precautions for switch statement in go language

  1. Support multi condition matching
  2. Different cases are not separated by break, and only one case will be executed by default.
  3. If you want to execute multiple case s, you need to use the fallthrough keyword, or you can terminate with break.
  4. Branches can also use expressions, for example: a > 10

golang for loop statement

The for loop in go language has only the for keyword, excluding while and do while in other languages

go language for loop syntax

for Initial statement;Conditional expression;End statement{
    Loop body statement
}

Note: for expressions do not need parentheses

go language for loop instance

Cycle output 1 to 10

func f() {
    for i := 1; i <= 10; i++ {
        fmt.Printf("i: %v\n", i)
    }
}

Operation results

i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
i: 10

Initial conditions can be written outside

func f() {
    i := 1
    for ; i <= 10; i++ {
        fmt.Printf("i: %v\n", i)
    }
}

Operation results

i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
i: 10

Both initial and end conditions can be omitted

func f() {
    i := 1 // initial condition 
    for i <= 10 {
        fmt.Printf("i: %v\n", i)
        i++ // End condition
    }
}

Operation results

i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
i: 10

This is similar to the while loop in other languages

Eternal cycle

func f() {
    for {
        fmt.Println("I've been doing it~")
    }
}

func main() {
    f()
}

Operation results

I've been doing it~
I've been doing it~
I've been doing it~
I've been doing it~
I've been doing it~
I've been doing it~
I've been doing it~
I've been doing it~
I've been doing it~
I've been doing it~
I've been doing it~
I've been doing it~
I've been doing it~
I've been doing it~
......

The for loop can be forced to exit the loop through break, goto, return and panic statements.

golang for range loop

In Go language, you can use for range to traverse arrays, slices, strings, map s and channel s. The return value traversed by for range has the following rules:

  1. Array, slice, string return index and value.
  2. map returns keys and values.
  3. Channel returns only the values within the channel.

go language for range instance

Circular array

func f() {
    var a = [5]int{1, 2, 3, 4, 5}
    for i, v := range a {
        fmt.Printf("i: %d, v: %v\n", i, v)
    }
}

func main() {
    f()
}

Operation results

i: 0, v: 1
i: 1, v: 2
i: 2, v: 3
i: 3, v: 4
i: 4, v: 5

Circular string

func f() {
    var s = "Multi course network, go course"
    for i, v := range s {
        fmt.Printf("i: %d, v: %c\n", i, v)
    }
    // %c output by character
}

func main() {
    f()
}

Operation results

i: 0, v: many
i: 3, v: course
i: 6, v: network
i: 9, v: ,
i: 12, v: g
i: 13, v: o
i: 14, v: teach
i: 17, v: Course

Circular slice

func f() {
    var s = []int{1, 2, 3, 4, 5}
    for i, v := range s {
        fmt.Printf("i, %d, v: %v\n", i, v)
    }
}

func main() {
    f()
}

Cyclic map

func f() {
    m := make(map[string]string)
    m["name"] = "tom"
    m["age"] = "20"
    m["email"] = "tom@gmail.com"
    for k, v := range m {
        fmt.Printf("k: %v, v: %v\n", k, v)
    }
}

func main() {
    f()
}

Operation results

k: email, v: tom@gmail.com
k: name, v: tom
k: age, v: 20

golang process control keyword break

The break statement can end blocks of code for, switch, and select.

Precautions for using break in go language

  1. There is no difference between using break in select alone and not using break.
  2. In the expression switch statement alone, and there is no fallhough, there is no difference between using break and not using break.
  3. Separate the switch statement in the expression and have a fallhough. Use break to terminate the execution of the case statement after the fallhough.
  4. The labeled break can jump out of the multi-layer select/ switch scope. It makes the break more flexible and the writing method more simple and flexible. It does not need to use control variables to jump out of the loop layer by layer. If there is no break, it can only jump out of the current statement block.

go language break keyword instance

Jump out of for loop

func f() {
    for i := 0; i < 10; i++ {
        if i == 5 {
            break // Exit loop
        }
        fmt.Printf("i: %v\n", i)
    }
}

func main() {
    f()
}

Operation results

i: 0
i: 1
i: 2
i: 3
i: 4

Jump out of switch

func f() {
    i := 2
    switch i {
    case 1:
        fmt.Println("Equal to 1")
        break
    case 2:
        fmt.Println("Equal to 2")
        break
        fallthrough
    case 3:
        fmt.Println("Equal to 3")
        break
    default:
        fmt.Println("Don't care")
        break
    }
}
func main() {
    f()
}

Operation results

Equal to 2

Comment out the break above fallthrough and run the result

Equal to 2
 Equal to 3

Jump to label

func f() {
MY_LABEL:
    for i := 0; i < 10; i++ {
        if i == 5 {
            break MY_LABEL
        }
        fmt.Printf("%v\n", i)
    }
    fmt.Println("end...")
}
func main() {
    f()
}

Operation results

0
1
2
3
4
end...

golang keywordcontinue

continue can only be used in the loop and go can only be used in the for loop. It can terminate this loop and proceed to the next loop.

When a label is added after the continue statement, it indicates that the cycle corresponding to the label is started.

go language continue instance

Output an even number between 1 and 10

func f() {
    for i := 0; i < 10; i++ {
        if i%2 == 0 {
            fmt.Printf("i: %v\n", i)
        }
    }
}
func main() {
    f()
}

Operation results

i: 0
i: 2
i: 4
i: 6
i: 8

Jump to label

func f() {
    // MY_LABEL:
    for i := 0; i < 5; i++ {
    MY_LABEL:
        for j := 0; j < 5; j++ {
            if i == 2 && j == 2 {
                continue MY_LABEL
            }
            fmt.Printf("i=%d,j=%d\n", i, j)
        }
    }
}
func main() {
    f()
}

Operation results

i=0,j=0
i=0,j=1
i=0,j=2
i=0,j=3
i=0,j=4
i=1,j=0
i=1,j=1
i=1,j=2
i=1,j=3
i=1,j=4
i=2,j=0
i=2,j=1
i=2,j=3
i=2,j=4
i=3,j=0
i=3,j=1
i=3,j=2
i=3,j=3
i=3,j=4
i=4,j=0
i=4,j=1
i=4,j=2
i=4,j=3
i=4,j=4

Pay attention to official account and learn more golang skills

Keywords: Go

Added by john_bboy7 on Wed, 08 Dec 2021 06:29:24 +0200