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. for
Loop
for
Loop is the only loop structure in Go language, but it is very flexible and can be used in a variety of scenarios:
Basicfor
Loop
for i := 0; i < 10; i++ { fmt.Println(i) }
This is a traditional `for` loop, initializing variables, setting conditions and incrementing variables.
for
Continuous 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 }
This loop continues to execute until the condition `sum
Infinite loop
If the condition is omitted, the `for` loop will execute infinitely:
for { fmt.Println("无限循环") }
This is useful in tasks that need to run continuously (such as servers).
-
if
Statement
if
Statement`if` statement is used for conditional execution.
Basicif
Statements
if x > 10 { fmt.Println("x大于10") }
if
statement with short statement
A short statement can be executed before the condition:
if x := 5; x < 10 { fmt.Println("x小于10") }
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") }
-
switch
Statement
switch
StatementThe `switch` statement is a powerful way to handle multiple conditions.
Basicswitch
Statements
switch os := runtime.GOOS; os { case "darwin": fmt.Println("OS X") case "linux": fmt.Println("Linux") default: fmt.Printf("%s.\n", os) }
switch
Execution order of statements
Go evaluates the cases of the `switch` statement from top to bottom, stopping once a match is successful.
Unconditionalswitch
Statement
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("晚上") }
-
defer
Statement
defer
StatementThe `defer` statement defers the execution of a function until its surrounding function returns.
Basicdefer
Statements
func main() { defer fmt.Println("world") fmt.Println("hello") }
Output:
<code>hello world</code>
Stackeddefer
Statements
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") }
Output:
<code>third second first</code>
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) }
Detailed explanation of steps
- **Task structure**: We define a `Task` structure containing `Name` and `Complete` fields.
- **Task List**: We create a slice of `Task` objects.
- **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.
- **switch statement**: We use the `switch` statement to check whether today is a weekend or a working day.
- **defer statement**: We use `defer` to print a message after all tasks are processed.
Best Practices
- **Use for loops wisely**: Since Go only has `for` loops, make sure to use them correctly. Avoid infinite loops unless necessary.
- **Keep if statements simple**: Use short statements in `if` conditions to make the code concise and easy to read.
- **Use switch to handle multiple conditions**: When dealing with multiple conditions, a `switch` statement is more readable than multiple `if-else` statements.
- **Use defer for cleanup**: `defer` is great for resource cleanup, such as closing files or releasing locks.
- **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!

WhentestingGocodewithinitfunctions,useexplicitsetupfunctionsorseparatetestfilestoavoiddependencyoninitfunctionsideeffects.1)Useexplicitsetupfunctionstocontrolglobalvariableinitialization.2)Createseparatetestfilestobypassinitfunctionsandsetupthetesten

Go'serrorhandlingreturnserrorsasvalues,unlikeJavaandPythonwhichuseexceptions.1)Go'smethodensuresexpliciterrorhandling,promotingrobustcodebutincreasingverbosity.2)JavaandPython'sexceptionsallowforcleanercodebutcanleadtooverlookederrorsifnotmanagedcare

AneffectiveinterfaceinGoisminimal,clear,andpromotesloosecoupling.1)Minimizetheinterfaceforflexibilityandeaseofimplementation.2)Useinterfacesforabstractiontoswapimplementationswithoutchangingcallingcode.3)Designfortestabilitybyusinginterfacestomockdep

Centralized error handling can improve the readability and maintainability of code in Go language. Its implementation methods and advantages include: 1. Separate error handling logic from business logic and simplify code. 2. Ensure the consistency of error handling by centrally handling. 3. Use defer and recover to capture and process panics to enhance program robustness.

InGo,alternativestoinitfunctionsincludecustominitializationfunctionsandsingletons.1)Custominitializationfunctionsallowexplicitcontroloverwheninitializationoccurs,usefulfordelayedorconditionalsetups.2)Singletonsensureone-timeinitializationinconcurrent

Gohandlesinterfacesandtypeassertionseffectively,enhancingcodeflexibilityandrobustness.1)Typeassertionsallowruntimetypechecking,asseenwiththeShapeinterfaceandCircletype.2)Typeswitcheshandlemultipletypesefficiently,usefulforvariousshapesimplementingthe

Go language error handling becomes more flexible and readable through errors.Is and errors.As functions. 1.errors.Is is used to check whether the error is the same as the specified error and is suitable for the processing of the error chain. 2.errors.As can not only check the error type, but also convert the error to a specific type, which is convenient for extracting error information. Using these functions can simplify error handling logic, but pay attention to the correct delivery of error chains and avoid excessive dependence to prevent code complexity.

TomakeGoapplicationsrunfasterandmoreefficiently,useprofilingtools,leverageconcurrency,andmanagememoryeffectively.1)UsepprofforCPUandmemoryprofilingtoidentifybottlenecks.2)Utilizegoroutinesandchannelstoparallelizetasksandimproveperformance.3)Implement


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools
