当前位置:网站首页>Go web programming practice (2) -- process control statement
Go web programming practice (2) -- process control statement
2022-07-02 21:01:00 【Li Yuanjing】
Catalog
Flow control statement
Every language will introduce process control statements ,Go Language also has these . Such as branch structure if-else、for loop 、for-range loop 、switch-case sentence 、goto sentence 、break Statements and continue sentence . below , Bloggers will give examples to introduce how to use .
if-else sentence
Basically ,Go Linguistic if-else Statements and Java The language is basically the same . such as , Here we use the size of the value , Choose output , The code is as follows :
func main() {
var b int=9
if b>9{
fmt.Println(" Greater than ")
}else if(b==9){
fmt.Println(" be equal to ")
}else{
fmt.Println(" Less than ")
}
}
for Loop statement
Different from other languages ,Go The language is only for loop , No, while and do-while loop . And its use method is similar to C The language is very close to . below , We cycle the output 1-100 Number , The code is as follows :
var i int
for i=0;i<=100 ;i++ {
fmt.Println(i)
}
use for Cycle to achieve do-while
Of course , If you want to use other languages do-while sentence , We can for The loop is written like this :
var i int=0
for{
i++
if i>50{
break
}
}
use for Cycle to achieve while
alike , We can also put for Cycle to achieve while The effect of the cycle , The code is as follows :
i :=0
for i<=10{
fmt.Println(i)
i++
}
break Specify to jump out of the loop
Did you learn C Linguistic , I should know Go Language can be used directly goto Jump to the specified code . and for Inside the loop , We can also pass break Statement directly determines which loop to terminate . such as :
var i,j int
JumpLoop1:
for i=1;i<100;i++{
JumpLoop2:
for j=0;j<i;j++{
fmt.Println(j)
if i>10{
break JumpLoop1
}else{
break JumpLoop2
}
}
}
Those who are interested can be deleted else Test them separately , Look at the end result . But generally speaking , If you don't specify JumpLoop1, Default to the innermost break Will only jump out of the innermost for loop .
continue sentence
Like any other language , Sometimes we just need to jump out of this cycle , therefore Go Language also provides us continue sentence . Of course ,continue Statements can also be followed by tags , For example, this cycle without jumping out of the innermost layer , And jump out of the outermost cycle , It can be written like this :
var i, j int
JumpTag:
for i = 1; i < 100; i++ {
for j = 0; j < i; j++ {
fmt.Println(j)
if i > 10 {
continue JumpTag
}
}
}
This code executes , To i=10,j=9 after , Only output 0. because i>10 when , The cycle is j=0 Output once , Out of the outermost cycle , Therefore, there will be no other value .
for-range loop
In other programming languages , We usually have a problem with map To iterate . alike ,Go Language provides us with for-range loop , It is also an iterative structure . The syntax is as follows :
for key,value :=range Composite variable value {
//.... Logical statement
}
Traversal array
First , We need to understand the definition of array , It is the same as the definition of ordinary variables , Just one more "[]" Number .
// No initial value definition
var num []int
// There is an initial value definition
var num =[]int{
1,2,3,4,5,6,7,8,9,0}
below , Let's show how to traverse the above array . The code is as follows :
// Traversal in the case of declaring an array
var num =[]int{
1,2,3,4,5,6,7,8,9,2}
for key,value :=range num{
fmt.Println("key=",key,"value=",value)
}
// Directly traverse the temporarily created array
for key,value :=range []int{
1,2,3,4,5,6,7,8,9,2}{
fmt.Println("key=",key,"value=",value)
}
Traversal string
Like some languages ,Go The string of a language is actually an array of single characters , We can also in the program , Yes Go String traversal . The code is as follows :
var name string="liyuanjinglyj"
for key,value :=range name{
fmt.Printf("key=%d , value=%c \n",key,value)
}
Traverse map
about map It's even simpler , When traversing ,key,value Exactly corresponding to its key value pair . The specific traversal method is as follows :
// obtain key,value
m:=map[string] string{
"name":"liyuanjing",
"age":"29",
}
for key,value :=range m{
fmt.Printf("key=%s , value=%s \n",key,value)
}
// Get only value
m:=map[string] string{
"name":"liyuanjing",
"age":"29",
}
for _,value :=range m{
fmt.Println(value)
}
In the second way key Change to "_", This underline is an anonymous variable , It can be understood as a placeholder . Anonymous variables themselves do not participate in space allocation , It doesn't take the name of a variable . alike , Also can be value Using anonymous variables , Get only key.
Traversal channel (channel)
What is a channel , We will introduce later , Here we define a channel directly , See how to traverse .
a := make(chan int)
go func() {
a <- 1
a <- 2
a <- 3
close(a)
}()
for v := range a {
fmt.Println(v)
}
The logic of the above code :
- Create an integer channel and instantiate
- By keyword go Start a goroutine
- Pass the number into the channel , The function is to push data into the channel 123
- End and close the channel
- use for-range Loop to channel a Traversal , That is, continue to receive data from the channel until the channel is closed
switch-case sentence
Go The language has improved C Linguistic switch-case sentence , The expression does not have to be constant , It doesn't even have to be an integer . and case And case Between them are independent code segments , No need to pass break Statement jumps out of the current case, To avoid execution to the next case.
var name =" Jay Chou "
switch name {
case " Jay Chou ":
fmt.Println(" singer ")
case " Wang Zhaojun ":
fmt.Println(" Messenger of reconciliation ")
default:
fmt.Println(" Check no one ")
}
The running result of the above code will only print the singer , No, break The following statement will not be executed , This blogger thinks Go The language design is good .
One branch has multiple values
Of course , Actually switch-case Statement case, It's not just about choosing one word , For example, some stars , Even if the actor is a singer , Do you use if and Judge ?
var name =" singer "
switch name {
case " singer "," actor ":
fmt.Println(" Jackson Yi ")
case " The writer ":
fmt.Println(" Yanye Qisheng ")
default:
fmt.Println(" Nothing ")
}
Branch expressions
case Statements can be more than constants , Can also be combined with if Add expressions as well . Examples are as follows :
var num =22
switch{
case num>0 && num==22 :
fmt.Println(" yes 22 you 're right ")
default:
fmt.Println(" Nothing ")
}
As shown in the above code ,switch under these circumstances , There is no need to add variables for judgment .
goto sentence
Go The most famous sentence in the language , Namely goto sentence . adopt goto Statement can jump directly to the specified label , Unconditional jump between codes . in addition ,goto Statements can also be used to jump out of a loop , Avoid repeated exits and other scenarios .
In the first article , We go through break Jump straight out to the outermost loop , Now we change the code at that time , Use goto To end the loop .
func main() {
var i, j int
for i = 1; i < 100; i++ {
for j = 0; j < i; j++ {
fmt.Println(j)
if i > 10 {
goto endTag
}
}
}
return
endTag:
fmt.Println(" The loop ends ")
}
As shown in the above code , We directly specify to jump to endTag At the label , This label is also named by yourself .
But here's the thing ,endTag There's a... on the label return, This is because if the conditions are not met, it will not be implemented endTag Tag statement , Otherwise , Even if it ends , The program will also be executed in sequence .
goto It's so convenient , What application scenarios do readers think of ?
I believe readers are in other languages , Thrown all kinds of exceptions , In particular, many network requests are actually abnormal , But is it very annoying to throw one after another ?
and goto It's easy , You can jump directly to the specified exception , In this way, all the same exceptions can be solved with one exception .
err :=getEmail()
if err !=nil{
goto endTag
}
err =getUser()
if err !=nil{
goto endTag
}
endTag:
fmt.Println(err)
// exception handling
here , We assume that there is 2 A way , Get user name and mailbox , But in fact, they throw the same exception , Then you can jump directly to the specified label , Handle the same exception . Instead of each throwing an exception and writing it again .
边栏推荐
- [fluent] dart function (function composition | private function | anonymous function | function summary)
- Select function
- kernel_ uaf
- sense of security
- In depth research and investment feasibility report of global and Chinese isolator industry, 2022-2028
- Taiwan SSS Xinchuang sss1700 replaces cmmedia cm6533 24bit 96KHz USB audio codec chip
- Exemple complet d'enregistrement du modèle pytoch + enregistrement du modèle pytoch seuls les paramètres d'entraînement sont - ils enregistrés? Oui (+ Solution)
- API documentation tool knife4j usage details
- Makefile: usage of control functions (error, warning, info)
- Want to ask, is there any discount for opening an account now? Is it safe to open an account online?
猜你喜欢
Cs5268 perfectly replaces ag9321mcq typec multi in one docking station solution
kernel tty_ struct
Investment strategy analysis of China's electronic information manufacturing industry and forecast report on the demand outlook of the 14th five year plan 2022-2028 Edition
kernel_ uaf
Web3js method to obtain account information and balance
Second hand housing data analysis and prediction system
Summary of interview experience, escort your offer, full of knowledge points
Redis sentinel cluster working principle and architecture deployment # yyds dry goods inventory #
Share the easy-to-use fastadmin open source system - Installation
An analysis of the past and present life of the meta universe
随机推荐
Research Report on the overall scale, major manufacturers, major regions, products and applications of building automation power meters in the global market in 2022
现在券商的优惠开户政策什么?实际上网上开户安全么?
Detailed upgrade process of AWS eks
Codeforces Round #771 (Div. 2)(A-C)
Function, function, efficiency, function, utility, efficacy
pytorch 模型保存的完整例子+pytorch 模型保存只保存可训练参数吗?是(+解决方案)
Sweet talk generator, regular greeting email machine... Open source programmers pay too much for this Valentine's day
Jetson XAVIER NX上ResUnet-TensorRT8.2速度与显存记录表(后续不断补充)
Sometimes only one line of statements are queried, and the execution is slow
Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of shock absorber oil in the global market in 2022
Sword finger offer (II) -- search in two-dimensional array
A river of spring water flows eastward
Write the content into the picture with type or echo and view it with WinHex
股票开户要找谁?手机开户是安全么?
An analysis of the past and present life of the meta universe
疫情封控65天,我的居家办公心得分享 | 社区征文
Spark source code compilation, cluster deployment and SBT development environment integration in idea
sense of security
Properties of expectation and variance
Check the confession items of 6 yyds