Home >Backend Development >Golang >Detailed explanation of Golang flow control statements

Detailed explanation of Golang flow control statements

WBOY
WBOYOriginal
2024-04-03 15:42:01816browse

There are three types of flow control statements in the Go language: conditional statements, loop statements and jump statements. Conditional statements control program flow based on the true or false value of a Boolean expression; loop statements are used to repeatedly execute a block of code; jump statements are used to explicitly control program flow, including exiting the loop, skipping iterations, or jumping to a specified location.

Detailed explanation of Golang flow control statements

Flow control statements in Go language

Flow control statements are used to control the flow of the program. There are three types in Go Flow control statement:

1. Conditional statement

Conditional statement determines the program flow based on the true or false value of a Boolean expression.

Grammar:

if <boolean expression> {
  // 如果条件为真,执行此代码块
} else if <boolean expression> {
  // 如果第一个条件为假,则执行此代码块
} else {
  // 如果所有条件都为假,执行此代码块
}

Example:

if age >= 21 {
  fmt.Println("允许饮酒")
} else {
  fmt.Println("禁止饮酒")
}

2. Loop statement

Loop statements are used to repeatedly execute a block of code.

Syntax:

for loop:

for <initialization>; <condition>; <post-statement> {
  // 循环体
}

while loop:

while <condition> {
  // 循环体
}

for range loop:

for range <iterable> {
  // 循环体
}

Example:

// for 循环
for i := 0; i < 5; i++ {
  fmt.Println(i)
}

// while 循环
total := 0
while total < 100 {
  total += 10
}

// for range 循环
numbers := []int{1, 2, 3, 4, 5}
for _, num := range numbers {
  fmt.Println(num)
}

3. Jump statement

Jump statements are used to explicitly control program flow.

Syntax:

break: Exit the most recent loop or switch statement.
continue: Skip the current loop iteration and continue with the next iteration.
goto: Jump to the specified location.

Example:

// break
for i := 0; i < 10; i++ {
  if i == 5 {
    break
  }
  fmt.Println(i)
}

// continue
for i := 0; i < 10; i++ {
  if i % 2 == 0 {
    continue
  }
  fmt.Println(i)
}

// goto
// 注意:不应在 Go 中滥用 goto
goto end
fmt.Println("此行不会被执行")
end:
fmt.Println("程序结束")

The above is the detailed content of Detailed explanation of Golang flow control statements. 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