当前位置:网站首页>Go language slow entry - process control statement
Go language slow entry - process control statement
2022-07-28 16:59:00 【zy010101】
Flow control statement
go The flow control statement of is very distinctive .if-else,for,switch-case. Be careful go No, while and do-while sentence . besides go There are also process control modules bound to specific types . for example , For container type for-range loop . go Support break,continue as well as goto sentence , in addition go Also supports unique fallthrough sentence .
if-else sentence
go In language if-else The statement format is as follows :
if InitSimpleStatement; Condition {
// do something
} else {
// do something
}The following points need to be explained .
- InitSimpleStatement Part is optional , If it is not omitted , Then it must be a simple statement . If it is omitted , It can be regarded as an empty statement ( A kind of simple statement ).
- Condition Must be an expression with a boolean result
- keyword if and else Left brace after { Must be on the same line as the keyword , If you use else-if structure , Then the closing brace of the previous code block } It has to be with else-if Keywords on the same line . Both of these rules are enforced by the compiler . So the following way, which is often written in other languages, is go The language is wrong .
const a = 10
if a{ // condition The result of must be Boolean .
} else {
}List of simple statement types
Go There are six simple statement types in :
- Variable short declaration statement .
- Pure assignment statement , Include x += y This form of operation .
- There are function or method calls that return results , And the receiving data operation of the channel .
- Channel sending data operation .
- Empty statement .
- Self increasing (x++) Self decrement (x–) sentence . Similar to other languages ,if-else Statements can be followed by multiple else-if Come on , for example :
if x{ // condition The result of must be Boolean .
//do
} else if y{
//do
}else{
//do
}for loop
stay go In language ,for The cycle form is as follows :
for InitSimpleStatement; Condition; PostSimpleStatement {
// do something
}go There is no while and do-while, Circulation can only be used for To solve . therefore , It has the following characteristics .
- InitSimpleStatement( Initialization statement ) and PostSimpleStatement( End of step statement ) Both parts must be simple statements , also PostSimpleStatement Cannot declare a short statement for a variable .
- Condition Must be an expression with a boolean result ( It is called a conditional expression ).
- All three parts just mentioned are optional
- In a for Circulation process control , If InitSimpleStatement and PostSimpleStatement Both parts are omitted at the same time ( Treat them as empty statements ), Then the two semicolons adjacent to them can also be omitted . Now , And in other languages while The cycle looks the same .
- In a for Circulation process control , If the conditional expression part is omitted , Then the compiler regards it as true.
- Every for Process control includes at least two sub code blocks . One of them is implicit , The other is explicit ( The beginning and end of curly braces , Also known as circulatory body ). This explicit code block is embedded in an implicit code block . The following code is equivalent .
for ; true; {
}
for true {
}
for ; ; {
}
for {
}For example, the following code prints out 012, instead of 0.
for i := 0; i < 3; i++ {
fmt.Print(i)
i := i // The variables declared here i Obscured the above statement i.
// Dexter i For the loop variable declared above i.
i = 10 // The newly declared i Has been changed .
_ = i
}break sentence
break Statements can be used to jump out ahead of time containing this break The innermost layer of a statement for loop . break Can be used in a switch-case Jump out of this in advance in any branch code block of process control switch-case Process control .
continue sentence
continue The statement can be used to terminate this in advance continue The innermost layer of a statement for Current cycle step of the cycle .
switch-case sentence
go Medium switch-case The complete form of the statement is as follows :
switch InitSimpleStatement; CompareOperand0 {
case CompareOperandList1:
// do something
case CompareOperandList2:
// do something
...
case CompareOperandListN:
// do something
default:
// do something
}- InitSimpleStatement Part must be a simple statement , It's optional .
- CompareOperand0 Part must be an expression ( If it is not omitted , See below ). The evaluation result of this expression is always regarded as a type determined value . If it is a type uncertain value , Then it is regarded as the type determination value of its default type . on this account , This expression cannot be of indeterminate type nil value . CompareOperand0 Is often referred to as switch expression .
- Every CompareOperandListX part (X Express 1 To N) Must be used for one ( english ) Comma separated expression list . Each of these expressions must be able to CompareOperand0 Compare expressions . Each such expression is often called case expression . If one case An expression is a type uncertain value , Then it must be able to automatically and implicitly convert to the corresponding switch The type of expression , Otherwise, the compilation will fail .
- Every case CompareOperandListX: Part and default: Then an implicit code block is formed . Each such implicit code block corresponds to case CompareOperandListX: perhaps default: Formed a branch . Each branch is optional .
One switch-case Examples of process control :
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
switch n := rand.Intn(100); n%9 {
case 0:
fmt.Println(n, "is a multiple of 9.")
// Unlike many other languages , The program will not automatically start from a
// The branch code block jumps to the next branch code block to execute .
// therefore , There is no need for one break sentence .
case 1, 2, 3:
fmt.Println(n, "mod 9 is 1, 2 or 3.")
break // there break Statements are optional , effect
// It's the same . Execution will not jump to the next branch .
case 4, 5, 6:
fmt.Println(n, "mod 9 is 4, 5 or 6.")
// case 6, 7, 8:
// The previous line may not compile , because 6 And the last one case Medium
// 6 repeated . Whether it can be compiled depends on the specific compiler implementation .
default:
fmt.Println(n, "mod 9 is 7 or 8.")
}
}If you want C/C++ in switch The statement does not use break The effect of statement , have access to fallthrough Statement to implement .
- One fallthrough The statement must be the last statement in a branch code block .
- One fallthrough Statements cannot appear in a switch-case In the last branch code block in process control .
such as , Several of the following code fallthrough Use is illegal .
switch n := rand.Intn(100) % 5; n {
case 0, 1, 2, 3, 4:
fmt.Println("n =", n)
// This whole if The code block is the last statement in the current branch
if true {
fallthrough // error: Not the last statement in the current branch
}
case 5, 6, 7, 8:
n := 99
fallthrough // error: Not the last statement in the current branch
_ = n
default:
fmt.Println(n)
fallthrough // error: Cannot appear in the last branch
}One switch-case In process control InitSimpleStatement Statement and CompareOperand0 Expressions are optional . If CompareOperand0 The expression is omitted , Then it is considered to be of type bool Type of true value . If InitSimpleStatement The statement is omitted , The semicolon that follows can also be omitted .
Reference material
https://gfw.go101.org/article/control-flows.html
https://learnku.com/docs/the-way-to-go/chapter-description/3591
边栏推荐
- Some opinions on bug handling
- Exercise note 5 (square of ordered array)
- leetcode647. 回文子串
- 深入理解 DeepSea 和 Salt 部署工具 – Storage6
- Do you really understand CMS garbage collector?
- 概率论与数理统计第一章
- 【深度学习】:《PyTorch入门到项目实战》第五天:从0到1实现Softmax回归(含源码)
- epoll水平出发何边沿触发
- Efficiency comparison of three methods for obtaining timestamp
- Leetcode daily practice - the number of digits in the offer 56 array of the sword finger
猜你喜欢

在AD中添加差分对及连线

Leetcode daily practice - 160. Cross linked list

HTAP是有代价的

Cluster construction and use of redis5

Microsoft: edge browser has built-in disk cache compression technology, which can save space and not reduce system performance

小程序:scroll-view默认滑倒最下面

Jsonarray traversal

技术分享 | 误删表以及表中数据,该如何恢复?

综合设计一个OPPE主页--页面服务部分

【深度学习】:《PyTorch入门到项目实战》第五天:从0到1实现Softmax回归(含源码)
随机推荐
Oracle system composition
有趣的 Kotlin 0x09:Extensions are resolved statically
HTAP是有代价的
Leetcode9. Palindromes
向高通支付18亿美元专利费之后,传华为向联发科订购了1.2亿颗芯片!官方回应
Ruoyi集成flyway后启动报错的解决方法
综合设计一个OPPE主页--页面的售后服务
给定正整数N、M,均介于1~10 ^ 9之间,N <= M,找出两者之间(含N、M)的位数为偶数的数有多少个
Implementation of transfer business
微软:Edge 浏览器已内置磁盘缓存压缩技术,可节省空间占用且不降低系统性能
Signal shielding and processing
Ruoyi's solution to error reporting after integrating flyway
结构化设计的概要与原理--模块化
parseJson
[deep learning]: day 4 of pytorch introduction to project practice: realize logistic regression from 0 to 1 (with source code)
Analysis of echo service model in the first six chapters of unp
Interesting kotlin 0x06:list minus list
Nowcode- learn to delete duplicate elements in the linked list (detailed explanation)
时间复杂度
Learn to use MySQL explain to execute the plan, and SQL performance tuning is no longer difficult