Home  >  Article  >  Backend Development  >  golang process control

golang process control

WBOY
WBOYOriginal
2023-05-13 11:12:37419browse

Golang is an efficient and modern programming language that provides rich features in process control. This article will explore the flow control structures in Golang, including conditional statements, loop statements and jump statements, to help readers better understand and apply these structures.

Conditional statements

Conditional statements in Golang include if statements, switch statements and select statements.

  1. if statement

if statement is used for conditional judgment. The syntax is as follows:

if condition {
    statement(s)
} else if condition {
    statement(s)
} else {
    statement(s)
}

where condition is a conditional expression used for judgment. true and false. If the condition is true, the statement block following if is executed; otherwise, the statement block is skipped and the next statement is executed.

If condition is followed by the else if keyword, each conditional expression will be evaluated in order and the first statement block that is true will be executed. If all conditional expressions are false, the block of statements following the else is executed. Without the else block, no statement is executed if the condition is false.

The following is an example of an if statement:

package main

import "fmt"

func main() {
    var a int = 10
    if a < 20 {
        fmt.Printf("a 小于 20
")
    }
    fmt.Printf("a 的值为 : %d
", a)
}

Output result:

a 小于 20
a 的值为 : 10
  1. switch statement

switch statement is used for multiple Conditional judgment, the syntax is as follows:

switch expression {
    case value1:
        statement(s)
    case value2:
        statement(s)
    case value3:
        statement(s)
    default:
        statement(s)
}

Among them, expression is an expression used to match the constants or variables in the case clause. If the match is successful, the corresponding statement block is executed; otherwise, the statement block is skipped and the next case clause (if one exists) is executed.

If all case clauses are not matched successfully, the statement block following default will be executed. If there is no default clause, no statements are executed.

The following is an example of a switch statement:

package main

import "fmt"

func main() {
    var grade string = "B"
    var marks int = 90

    switch marks {
        case 90:
            grade = "A"
        case 80:
            grade = "B"
        case 60, 70:
            grade = "C"
        default:
            grade = "D"
    }

    switch {
        case grade == "A" :
            fmt.Printf("优秀!
" )
        case grade == "B", grade == "C" :
            fmt.Printf("良好
" )
        case grade == "D" :
            fmt.Printf("及格
" )
        case grade == "F":
            fmt.Printf("不及格
" )
        default:
            fmt.Printf("差
" )
    }
    fmt.Printf("你的等级是 %s
", grade )
}

Output result:

良好!
你的等级是 B
  1. select statement

select statement is used at the same time To monitor multiple channels, the syntax is as follows:

select {
    case communication clause 1:
        statement(s)
    case communication clause 2:
        statement(s)
    .............
    default:
        statement(s)
}

Among them, communication clause refers to a channel or a channel operation with direction, including sending operation and receiving operation. If a channel has data that can be read or written, the corresponding statement block is executed; otherwise, the channel is skipped and the next communication clause is executed. If no data is readable or writable on any channel, the statement block following default is executed.

The following is an example of a select statement:

package main

import "fmt"

func fibonacci(c, quit chan int) {
    x, y := 0, 1
    for {
        select {
        case c <- x:
            x, y = y, x+y
        case <-quit:
            fmt.Println("quit")
            return
        }
    }
}

func main() {
    c := make(chan int)
    quit := make(chan int)
    go func() {
        for i := 0; i < 10; i++ {
            fmt.Println(<-c)
        }
        quit <- 0
    }()
    fibonacci(c, quit)
}

Output result:

0
1
1
2
3
5
8
13
21
34
quit

Loop statement

The loop statement in Golang includes the for statement and the range statement .

  1. for statement

The for statement is used to execute a piece of code in a loop. The syntax is as follows:

for init; condition; post {
    statement(s);
}

Among them, init is used for when to start the loop, condition It is used to determine whether the loop continues, and post is used to control the operation of loop variables.

The following is an example of a for statement:

package main

import "fmt"

func main() {
    var b int = 15
    var a int

    for i := 0; i < 10; i++ {
        fmt.Printf("i 的值为: %d
", i)
    }

    for a < b {
        a++
        fmt.Printf("a 的值为: %d
", a)
    }
}

Output result:

i 的值为: 0
i 的值为: 1
i 的值为: 2
i 的值为: 3
i 的值为: 4
i 的值为: 5
i 的值为: 6
i 的值为: 7
i 的值为: 8
i 的值为: 9
a 的值为: 1
a 的值为: 2
a 的值为: 3
a 的值为: 4
a 的值为: 5
a 的值为: 6
a 的值为: 7
a 的值为: 8
a 的值为: 9
a 的值为: 10
a 的值为: 11
a 的值为: 12
a 的值为: 13
a 的值为: 14
a 的值为: 15
  1. range statement

range statement is used for traversal Elements of arrays, slices, channels or maps, the syntax is as follows:

for key, value := range oldMap {
    newMap[key] = value
}

Among them, key and value represent the key and value of the current element respectively.

The following is an example of a range statement:

package main

import "fmt"

func main() {
    nums := []int{2, 3, 4}
    sum := 0
    for _, num := range nums {
        sum += num
    }
    fmt.Println("sum:", sum)

    for i, num := range nums {
        if num == 3 {
            fmt.Println("index:", i)
        }
    }

    kvs := map[string]string{"a": "apple", "b": "banana"}
    for k, v := range kvs {
        fmt.Printf("%s -> %s
", k, v)
    }
}

Output result:

sum: 9
index: 1
a -> apple
b -> banana

Jump statement

Jump statements in Golang include break and continue and goto.

  1. break statement

The break statement is used to interrupt the loop body. The syntax is as follows:

for i := 0; i < 10; i++ {
    if i == 5 {
        break
    }
    fmt.Printf("%d ", i)
}
fmt.Println()

Output result:

0 1 2 3 4
  1. continue statement

continue statement is used to interrupt this iteration of the current loop body. The syntax is as follows:

for i := 0; i < 10; i++ {
    if i == 5 {
        continue
    }
    fmt.Printf("%d ", i)
}
fmt.Println()

Output result:

0 1 2 3 4 6 7 8 9
  1. goto statement

The goto statement is used to unconditionally jump to a certain code label (label) for execution. The syntax is as follows:

goto label;
...
label: statement

where label is an identifier and statement is an execution statement.

The following is an example of a goto statement:

package main

import "fmt"

func main() {
    i := 0
Again:
    fmt.Printf("循环执行次数:%d
", i)
    i++
    if i < 10 {
        goto Again
    }
}

Output result:

循环执行次数:0
循环执行次数:1
循环执行次数:2
循环执行次数:3
循环执行次数:4
循环执行次数:5
循环执行次数:6
循环执行次数:7
循环执行次数:8
循环执行次数:9

Summary

The flow control structure in Golang includes conditional statements and loop statements and jump statements. Conditional statements include if, switch and select statements, which are used to make single or multi-condition judgments. Loop statements include for and range statements, which are used to loop through a piece of code or traverse an element. Jump statements include break, continue, and goto statements, which are used to interrupt the current loop or unconditionally jump to a label for execution. In actual programming, it is necessary to flexibly select the appropriate process control structure according to needs to implement code logic.

The above is the detailed content of golang process control. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Is golang easy to learn?Next article:Is golang easy to learn?