Table of Contents
Core Concept
1. forLoop
BasicforLoop
Home Backend Development Golang Flow Control Statements in Go

Flow Control Statements in Go

Jan 22, 2025 pm 08:10 PM

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

for i := 0; i < 10; i++ {
    fmt.Println(i)
}
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:

sum := 1
for sum < 100 {
    sum += sum
}
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:

for {
    fmt.Println("无限循环")
}
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

if x > 10 {
    fmt.Println("x大于10")
}
Copy after login

if statement with short statement

A short statement can be executed before the condition:

if x := 5; x < 10 {
    fmt.Println("x小于10")
}
Copy after login

if and else

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

if x > 10 {
    fmt.Println("x大于10")
} else if x == 10 {
    fmt.Println("x等于10")
} else {
    fmt.Println("x小于10")
}
Copy after login

  1. switchStatement

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

BasicswitchStatements

switch os := runtime.GOOS; os {
case "darwin":
    fmt.Println("OS X")
case "linux":
    fmt.Println("Linux")
default:
    fmt.Printf("%s.\n", os)
}
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`:

t := time.Now()
switch {
case t.Hour() < 12:
    fmt.Println("上午")
case t.Hour() < 18:
    fmt.Println("下午")
default:
    fmt.Println("晚上")
}
Copy after login

  1. deferStatement

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

BasicdeferStatements

func main() {
    defer fmt.Println("world")
    fmt.Println("hello")
}
Copy after login

Output:

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

StackeddeferStatements

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

func main() {
    defer fmt.Println("first")
    defer fmt.Println("second")
    defer fmt.Println("third")
}
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.

for i := 0; i < 10; i++ {
    fmt.Println(i)
}
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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Golang's Purpose: Building Efficient and Scalable Systems Golang's Purpose: Building Efficient and Scalable Systems Apr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang and C  : Concurrency vs. Raw Speed Golang and C : Concurrency vs. Raw Speed Apr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Golang's Impact: Speed, Efficiency, and Simplicity Golang's Impact: Speed, Efficiency, and Simplicity Apr 14, 2025 am 12:11 AM

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Golang and C  : The Trade-offs in Performance Golang and C : The Trade-offs in Performance Apr 17, 2025 am 12:18 AM

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

The Performance Race: Golang vs. C The Performance Race: Golang vs. C Apr 16, 2025 am 12:07 AM

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

Golang vs. C  : Performance and Speed Comparison Golang vs. C : Performance and Speed Comparison Apr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

See all articles