Go language basics - if-else
##if is a statement with a Boolean condition, if the condition evaluates If the result is true, the code in the curly brackets after if will be executed. If the result is false, the code in the curly brackets after else will be executed.
Through this article, we will learn about the various syntax and usage of if statements.The syntax of the if statement is as follows:
if condition {
}If the condition is judged to be true, the execution will Code between brackets {}. Unlike other languages like C, braces {} are mandatory even if there is only one line of code between them. Let us write a simple program to determine whether a number is even or odd.
package main
import (
"fmt"
)
func main() {
num := 10
if num%2 == 0 { //checks if number is even
fmt.Println("The number", num, "is even")
return
}
fmt.Println("The number", num, "is odd")
}Execution[1]
Line 9 of the above code num%2 determines whether the remainder after dividing num by 2 is 0, because num times It is an even number, so the remainder is 0, and the program outputs The number 10 is even.The if statement has a corresponding else branch. If the condition result is false, the else branch will be executed.
if condition {
} else {
}In the above code, if the condition result is false, the lines of code between the else branch {} will be executed. Let's rewrite the program to determine whether a number is odd or even using if-else statements. package main
import (
"fmt"
)
func main() {
num := 11
if num%2 == 0 { //checks if number is even
fmt.Println("the number", num, "is even")
} else {
fmt.Println("the number", num, "is odd")
}
}Execution[2]
In the above code, we did not return directly when the condition is true, but created an else statement , when the condition is false, the statement will be executed. In our case, since 11 is an odd number, the if condition is false, so the code in the else statement will be executed.上面代码执行输出:
the number 11 is odd
if-else if-else 语句
if 语句不仅有 else 分支,还可以有 else-if 分支,语法如下:
if condition1 {
...
} else if condition2 {
...
} else {
...
}代码执行时会从上之下判断每个分支的 condition 是否为 true。
上面的代码,如果 condition1 为 true,将会执行 condition1 后面 {} 之间的代码;
如果 condition1 为 false 且 condition2 为 true,则会执行 condition2 后面 {} 之间的代码;
如果 condition1 和 condition2 都为 false,则会执行 else 后面 {} 之间的代码。
可以有任意数量的 else-if 语句块。
通常,只要 if 和 else-if 语句有一个 condition 为 true,就会执行相应的代码块,如果没有为 true 的情况则会执行 else 分支的代码。
我们使用 else-if 语句编写一段程序:
package main
import (
"fmt"
)
func main() {
num := 99
if num <= 50 {
fmt.Println(num, "is less than or equal to 50")
} else if num >= 51 && num <= 100 {
fmt.Println(num, "is between 51 and 100")
} else {
fmt.Println(num, "is greater than 100")
}
}执行[3]
上面的代码,else if num >= 51 && num <= 100 条件为 true,所以执行输出:
99 is between 51 and 100
if 包含初始化语句
if 语句的一种变体是在判断条件之前,可以有短变量声明语句,语法如下:
if assignment-statement; condition {
}上面的代码片段,短变量声明语句会优先执行。
我们用上面的语法重写代码来判断数字是偶数还是奇数。
package main
import (
"fmt"
)
func main() {
if num := 10; num % 2 == 0 { //checks if number is even
fmt.Println(num,"is even")
} else {
fmt.Println(num,"is odd")
}
}执行[4]
上面代码第 8 行,变量 num 在 if 语句中被初始化,
需要注意的是,num 的作用域仅限于 if-else 语句块内,即如果我们在 if-else 之外访问 num,编译器将会报错。
当我们仅仅想声明一个只在 if-else 内部使用的变量时,这种语法就可以派上用场,可确保变量的作用范围仅在 if-else 语句内。
坑
else 语句应该在 if 语句的右大括号 } 之后的同一行开始。如果不是,会编译报错。
写一小段程序理解下:
package main
import (
"fmt"
)
func main() {
num := 10
if num % 2 == 0 { //checks if number is even
fmt.Println("the number is even")
}
else {
fmt.Println("the number is odd")
}
}执行[5]
上面代码的第 11 行,else 语句没有紧跟着 if 语句的 } 后面 ,相反,它是另起新的一行开始。如果你执行程序编译器将会报错。
./prog.go:12:5: syntax error: unexpected else, expecting }
报错的原因在于 Go 会自动插入分号,关于插入分号的规则可以点击这里[6]查看更多信息。
其中有一项规则,如果一行代码以 } 结束,则会在 } 后面自动加上分号,所以上面代码第 11 行,会被编译器在 } 后面自动加上分号。
我们的代码就变成了:
...
if num%2 == 0 {
fmt.Println("the number is even")
}; //semicolon inserted by Go Compiler
else {
fmt.Println("the number is odd")
}由于 if-else 是一个独立的语句,中间不应出现分号,因此,程序编译会报错。因此,将 else 紧跟在 if 语句的右大括号 } 之后是语法要求。
正确格式的代码如下:
package main
import (
"fmt"
)
func main() {
num := 10
if num%2 == 0 { //checks if number is even
fmt.Println("the number is even")
} else {
fmt.Println("the number is odd")
}
}执行[7]
Go 里的习惯用法
我们已经学习了各种 if-else 语句,针对同一功能可以用这些不同语句编写出不同的实现方法。例如,我们使用 if-else 语句及其变体实现了不同的方式去判断一个数字是奇数还是偶数。你可能会问,哪种方式才是 Go 语言常用的方式呢?
在 Go 的设计哲学中,最好避免不必要的分支和代码缩进。执行时尽早返回也被认为是更好的。
再来展示下之前的代码:
package main
import (
"fmt"
)
func main() {
if num := 10; num % 2 == 0 { //checks if number is even
fmt.Println(num,"is even")
} else {
fmt.Println(num,"is odd")
}
}按照 Go 语言的设计哲学该如何编写上述的代码呢?应该尽量避免 else 分支;如果 if 语句的条件为 true,则应尽早执行 return 返回。
就像下面这样:
package main
import (
"fmt"
)
func main() {
num := 10;
if num%2 == 0 { //checks if number is even
fmt.Println(num, "is even")
return
}
fmt.Println(num, "is odd")
}
执行[8]
在上面代码中,一旦我们发现数字是偶数,就立即返回,就避免了不必要的 else 分支。这就是 Go 语言的哲学 -- “大道至简”,尽量追求代码简洁。
The above is the detailed content of Go language basics - if-else. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
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
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language?
Apr 02, 2025 pm 04:54 PM
The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...
What should I do if the custom structure labels in GoLand are not displayed?
Apr 02, 2025 pm 05:09 PM
What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...
In Go programming, how to correctly manage the connection and release resources between Mysql and Redis?
Apr 02, 2025 pm 05:03 PM
Resource management in Go programming: Mysql and Redis connect and release in learning how to correctly manage resources, especially with databases and caches...
centos postgresql resource monitoring
Apr 14, 2025 pm 05:57 PM
Detailed explanation of PostgreSQL database resource monitoring scheme under CentOS system This article introduces a variety of methods to monitor PostgreSQL database resources on CentOS system, helping you to discover and solve potential performance problems in a timely manner. 1. Use PostgreSQL built-in tools and views PostgreSQL comes with rich tools and views, which can be directly used for performance and status monitoring: pg_stat_activity: View the currently active connection and query information. pg_stat_statements: Collect SQL statement statistics and analyze query performance bottlenecks. pg_stat_database: provides database-level statistics, such as transaction count, cache hit
Go vs. Other Languages: A Comparative Analysis
Apr 28, 2025 am 12:17 AM
Goisastrongchoiceforprojectsneedingsimplicity,performance,andconcurrency,butitmaylackinadvancedfeaturesandecosystemmaturity.1)Go'ssyntaxissimpleandeasytolearn,leadingtofewerbugsandmoremaintainablecode,thoughitlacksfeatureslikemethodoverloading.2)Itpe
Common Use Cases for the init Function in Go
Apr 28, 2025 am 12:13 AM
ThecommonusecasesfortheinitfunctioninGoare:1)loadingconfigurationfilesbeforethemainprogramstarts,2)initializingglobalvariables,and3)runningpre-checksorvalidationsbeforetheprogramproceeds.Theinitfunctionisautomaticallycalledbeforethemainfunction,makin
How to use lowercase-named functions in different files within the same package?
Apr 02, 2025 pm 05:00 PM
How to use lowercase names in different files within the same package? On Go...
Backend development language performance PK: Which language saves the most resources?
Apr 02, 2025 pm 04:27 PM
Comparison of back-end development language performance: Discussion on resource utilization Selecting the right programming language and framework is crucial for back-end development, especially in resource profit...


