当前位置:网站首页>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 .
边栏推荐
- 疫情封控65天,我的居家办公心得分享 | 社区征文
- Basic concept of database, installation and configuration of database, basic use of MySQL, operation of database in the project
- Outsourcing for three years, abandoned
- 通信人的经典语录,第一条就扎心了……
- Send blessings on Lantern Festival | limited edition red envelope cover of audio and video is released!
- Backpack template
- [cloud native topic -50]:kubesphere cloud Governance - operation - step by step deployment of microservice based business applications - database middleware MySQL microservice deployment process
- Talk about macromolecule coding theory and Lao Wang's fallacy from the perspective of evolution theory
- Volvo's first MPV is exposed! Comfortable and safe, equipped with 2.0T plug-in mixing system, it is worth first-class
- Select function
猜你喜欢

Research Report on ranking analysis and investment strategic planning of RFID market competitiveness of China's industrial manufacturing 2022-2028 Edition
![[fluent] dart technique (independent main function entry | nullable type determination | default value setting)](/img/cc/3e4ff5cb2237c0f2007c61db1c346d.jpg)
[fluent] dart technique (independent main function entry | nullable type determination | default value setting)

Report on investment development and strategic recommendations of China's vibration isolator market, 2022-2027

API documentation tool knife4j usage details

Activation function - relu vs sigmoid
![[shutter] statefulwidget component (create statefulwidget component | materialapp component | scaffold component)](/img/04/4070d51ce8b7718db609ef2fc8bcd7.jpg)
[shutter] statefulwidget component (create statefulwidget component | materialapp component | scaffold component)

pytorch 模型保存的完整例子+pytorch 模型保存只保存可訓練參數嗎?是(+解决方案)

Add two numbers of leetcode

Customized Huawei hg8546m restores Huawei's original interface

Volvo's first MPV is exposed! Comfortable and safe, equipped with 2.0T plug-in mixing system, it is worth first-class
随机推荐
Go cache of go cache series
Research Report on the overall scale, major manufacturers, major regions, products and applications of battery control units in the global market in 2022
Research Report on ranking analysis and investment strategic planning of RFID market competitiveness of China's industrial manufacturing 2022-2028 Edition
Redis -- three special data types
Research Report on the overall scale, major manufacturers, major regions, products and applications of sliding door dampers in the global market in 2022
【QT】QPushButton创建
Friends who firmly believe that human memory is stored in macromolecular substances, please take a look
B-end e-commerce - reverse order process
Select function
The first of the classic quotations of correspondents is heartbreaking
Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of voltage source converters in the global market in 2022
Is it safe to buy funds on securities accounts? Where can I buy funds
How to open an account online? Is it safe to open a mobile account?
Don't you want to have a face-to-face communication with cloud native and open source experts? (including benefits
How to do interface testing? After reading this article, it will be clear
1007 maximum subsequence sum (25 points) "PTA class a exercise"
Taiwan SSS Xinchuang sss1700 replaces cmmedia cm6533 24bit 96KHz USB audio codec chip
Longest public prefix of leetcode
Cron expression (seven subexpressions)
kernel_ uaf