Home > Backend Development > Golang > Flow Control Statements in Go

Flow Control Statements in Go

Linda Hamilton
Release: 2025-01-22 20:10:11
Original
715 people have browsed it

Flow Control Statements in Go

The flow control statements of Go language are the basis of its programming. Like other languages, they control the program execution flow and implement decision-making, looping and resource management. This article takes an in-depth look at Go’s flow control statements, including for, if, switch, and defer, and explains how to use them effectively in Go programs.

This article is part of the Go language tutorial series, designed to help developers understand the Go language more deeply. Whether you are a beginner or an experienced developer, this guide will give you the knowledge you need to write more efficient and readable Go code.

After reading this article, you will master:

  • Different types of flow control statements in Go language.
  • How to use these statements in real situations.
  • Best practices and common pitfalls.

Let’s get started!

Core Concept

1. forLoop

forLoop is the only loop structure in Go language, but it is very flexible and can be used in a variety of scenarios:

BasicforLoop

<code class="language-go">for i := 0; i < 10; i++ {
    fmt.Println(i)
}</code>
Copy after login
Copy after login

This is a traditional `for` loop, initializing variables, setting conditions and incrementing variables.

forContinuous execution of loop (similar to while loop)

Go does not have the `while` keyword, but you can use a `for` loop to achieve the same effect:

<code class="language-go">sum := 1
for sum < 100 {
    sum += sum
}</code>
Copy after login

This loop continues to execute until the condition `sum < 100` is not true. < 100`不成立。

Infinite loop

If the condition is omitted, the `for` loop will execute infinitely:

<code class="language-go">for {
    fmt.Println("无限循环")
}</code>
Copy after login

This is useful in tasks that need to run continuously (such as servers).

  1. ifStatement

`if` statement is used for conditional execution.

BasicifStatements

<code class="language-go">if x > 10 {
    fmt.Println("x大于10")
}</code>
Copy after login

if statement with short statement

A short statement can be executed before the condition:

<code class="language-go">if x := 5; x < 10 {
    fmt.Println("x小于10")
}</code>
Copy after login

if and else

You can also use `else` and `else if`:

<code class="language-go">if x > 10 {
    fmt.Println("x大于10")
} else if x == 10 {
    fmt.Println("x等于10")
} else {
    fmt.Println("x小于10")
}</code>
Copy after login

  1. switchStatement

The `switch` statement is a powerful way to handle multiple conditions.

BasicswitchStatements

<code class="language-go">switch os := runtime.GOOS; os {
case "darwin":
    fmt.Println("OS X")
case "linux":
    fmt.Println("Linux")
default:
    fmt.Printf("%s.\n", os)
}</code>
Copy after login

switchExecution order of statements

Go evaluates the cases of the `switch` statement from top to bottom, stopping once a match is successful.

UnconditionalswitchStatement

The unconditional `switch` statement is equivalent to `switch true`:

<code class="language-go">t := time.Now()
switch {
case t.Hour() < 12:
    fmt.Println("上午")
case t.Hour() < 18:
    fmt.Println("下午")
default:
    fmt.Println("晚上")
}</code>
Copy after login

  1. deferStatement

The `defer` statement defers the execution of a function until its surrounding function returns.

BasicdeferStatements

<code class="language-go">func main() {
    defer fmt.Println("world")
    fmt.Println("hello")
}</code>
Copy after login

Output:

<code>hello
world</code>
Copy after login

StackeddeferStatements

Delay functions are executed in last-in-first-out (LIFO) order:

<code class="language-go">func main() {
    defer fmt.Println("first")
    defer fmt.Println("second")
    defer fmt.Println("third")
}</code>
Copy after login

Output:

<code>third
second
first</code>
Copy after login

Practical example

Let’s look at a practical example demonstrating the use of these flow control statements. We will create a simple program that processes a task list and prints its status.

<code class="language-go">for i := 0; i < 10; i++ {
    fmt.Println(i)
}</code>
Copy after login
Copy after login

Detailed explanation of steps

  1. **Task structure**: We define a `Task` structure containing `Name` and `Complete` fields.
  2. **Task List**: We create a slice of `Task` objects.
  3. **for loop**: We use a `for` loop to iterate over tasks. For each task, we use an `if` statement to check if it has been completed.
  4. **switch statement**: We use the `switch` statement to check whether today is a weekend or a working day.
  5. **defer statement**: We use `defer` to print a message after all tasks are processed.

Best Practices

  1. **Use for loops wisely**: Since Go only has `for` loops, make sure to use them correctly. Avoid infinite loops unless necessary.
  2. **Keep if statements simple**: Use short statements in `if` conditions to make the code concise and easy to read.
  3. **Use switch to handle multiple conditions**: When dealing with multiple conditions, a `switch` statement is more readable than multiple `if-else` statements.
  4. **Use defer for cleanup**: `defer` is great for resource cleanup, such as closing files or releasing locks.
  5. **Avoid Deep Nesting**: Deeply nested `if` or `for` statements can make the code difficult to read. Consider refactoring into a function.

Conclusion

Flow control statements are essential tools in the Go language. They allow you to control the execution flow of your program. By mastering `for`, `if`, `switch`, and `defer`, you can write more efficient, readable, and maintainable Go code.

I encourage you to try the examples provided in this article and experiment with the concepts on your own.

Call to Action

This article is part of the Go language tutorial series, designed to help you become a more proficient Go developer. If you found this article helpful, be sure to check out previous and upcoming tutorials in this series. Check it out on my blog or Dev.to.

Happy programming! ?

The above is the detailed content of Flow Control Statements in Go. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template