Go language basics four
We are going to study todayif statement, which is the judgment sentence that everyone mentioned, let’s take a look atDefinition of if statement
if definition
Conditional statements need to be passed by the developerSpecify one or more conditions,And determine whether the specified statement is true by testing whether the condition is true, and inIf the condition is false, another statement is executed. I believe that readers feel like they are in the fog when they see this. How can we express it?trueandfalseWoolen cloth?
Single-layer if syntax format
- Conditional expression brackets can be omitted.
- Holding the initialization statement, you can define local variables of the code block.
- The code block opening bracket must be at the end of the conditional expression.
if boolean expression {
/* Execute when the boolean expression is true */
}
What I want to introduce here to readers is that if the number given by the conditional statement program after if can satisfy it, then we represent it astrue
; If not, returnfalse
package main import "fmt" func main() { a := 3 if a > 2 { ("true") } else { ("false") } }
As shown in the code block, here weDefines a value of 3, next is an if judgment, ifThis value >2, then call the function to print the outputtrue
; otherwise returnfalse
. In other words, here we areA judgment on the a variable, as for the content of the calling function printout, it is up to the reader to decide
Grammar Warning
In Go syntax,Tripartite operators (trigonomic operators) a > b ? a : b, If readers are interested in ternary operators, they can move to Java to learn about ternary operators (whichIn essence, it is also a form of if judgment)
package main import "fmt" func main() { /* Define local variables */ var a int = 10 /* Use if statement to judge a Boolean expression */ if a < 20 { /* If the condition is true, execute the following statement */ ("a is less than 20\n" ) } ("The value of a is : %d\n", a) }
The above is aboutif judgmentReaders can experience it by themselves;if
In the boolean expressiontrue
hour,The following statement block executes, iffalse
Then executeelse
Statement block.
package main import "fmt" func main() { /* Local variable definition */ var a int = 100 /* Judge Boolean expression */ if a < 20 { /* If the condition is true, execute the following statement */ ("a is less than 20\n" ) } else { /* If the condition is false, execute the following statement */ ("a is not less than 20\n" ) } ("The value of a is : %d\n", a) }
existGo language
middle,ifThe statement is alsoSupport nested processing, that is, it can be realizedMultiple if judgmentsTo achieve the desired results of the program
Multi-layered if syntax format
if boolean expression 1 {
/* Execute when Boolean expression 1 is true */
if boolean expression 2 {
/* Execute when Boolean expression 2 is true */
}
}
package main import "fmt" func main() { /* Define local variables */ var a int = 100 var b int = 200 /* Judgment conditions */ if a == 100 { /* if conditional statement is true Execute */ if b == 200 { /* if conditional statement is true Execute */ ("The value of a is 100, and the value of b is 200\n" ) } } ("a value is : %d\n", a ) ("The value of b is : %d\n", b ) }
As shown in the picture above, weif
Nested in the statementAnother if statement, that isWrite the judgment on the value of variable b when the default a == 100, the final call to the functionPrint out the values of a and b
Sometimes weMultiple variables match the same value, will use itSwitch
Statement
Switch definition
switch
Statements are used to perform different actions based on different conditions, eachcase
The branches are unique, tested one by one from top to bottom until they match.Golang switch
Branch expressionsCan be of any type, not limited to constants. Can be omittedbreak
, automatically terminated by default.
Switch syntax format
switch var1 { case val1: ... case val2: ... default: ... }
package main import "fmt" func main() { /* Define local variables */ var grade string = "B" var marks int = 90 switch marks { case 90: grade = "A" case 80: grade = "B" case 50,60,70 : grade = "C" default: grade = "D" } switch { case grade == "A" : ("Excellent!\n" ) case grade == "B", grade == "C" : ("Good\n" ) case grade == "D" : ("Pass\n" ) case grade == "F": ("Failed\n" ) default: ("Poor\n" ) } ("Your level is %s\n", grade ) }
From the above code block, we define two local variablesgradeandmarks,rightmarksconductSwitch
Judgment operation, whencase
When different values are met, the values printed by calling the function are also different.
Type Switch
switch
Statements can also be used fortype-switch
To judge a certaininterfaceIn variablesThe actual stored variable type
Type Switch syntax format
switch x.(type){ case type: statement(s) case type: statement(s) /* You can define any number of cases */ default: /* Optional */ statement(s) }
becauseType Switch
There are not many uses, so the author will not give a detailed description here. Readers can search for relevant documents on the official website for learning.
Select definition
-
select
The statement is similar toswitch
statement, butselect
A runnable will be executed randomlycase
. If notcase
Can be run,It will block, until there iscase
Can be run. -
select
yesGo
One control structure in the same way as theswitch
Statement. Eachcase
Must be a communication operation, either send or receive。 -
select
Randomly execute a runnablecase
. If notcase
Can be run,It will block, until there iscase
Can be run.A default clause should always be runnable。
Select syntax format
select { case communication clause : statement(s); case communication clause : statement(s); /* You can define any number of cases */ default : /* Optional */ statement(s); }
Notes on Select statements
- Each
case
AllMust be a communication - all
channel
Expressions will be evaluated - All sent expressions will be evaluated
- If any communication can be performed, it will be executed; others are ignored。
- If there are multiple
case
All can be run, Select will randomly and fairly select an execution. Others will not be executed. - If there is
default
clause, execute the statement. - If not
default
Words,select
Willblock, until a certain communication can be run;Go
Will not be corrected againchannel
The value is re-evaluated.
package main import "fmt" func main() { var c1, c2, c3 chan int //Channel mechanism var i1, i2 int select { case i1 = <-c1: ("received ", i1, " from c1\n") case c2 <- i2: ("sent ", i2, " to c2\n") case i3, ok := (<-c3): // same as: i3, ok := <-c3 if ok { ("received ", i3, " from c3\n") } else { ("c3 is closed\n") } default: ("no communication\n") } }
According to the above code,c1、c2、c3
Three variables, and usechan
aisle.Explanation of writing: One can be sentint
Type of datachannel
Generally written aschan int
, according to the grammar rules above: if there isdefault
The clause is executed, so the code execution code above is:no communication
Select Usage Supplement
- We can use
select
Come and listenchannel
Data flow -
select
Usage andswitch
The syntax is very similar,select
Start a new selection block, each selection condition iscase
Statement to describe -
switch
StatementAny comparison condition can be selected using equal comparison,select
There are many restrictions, the biggest one is eachcase
There must be one in the statementIO operation
- If each
case
None of them are read,Go language
Will be read automaticallydefault
What the statement describes,Under normal circumstances, eachselect
The program will have an output statement - If neither
case
The statement satisfies it, and it does not existdefault
statement,The program enters a blocking state,The system will issue a warning until it is cleared
Timeout judgment
var resChan = make(chan int) // do request func test() { select { case data := <-resChan: doData(data) case <-( * 3): ("request time out") } } func doData(data int) { //... }
According to the above code block, we have defined aselect
Statement, in the firstcase
Inside, we willresChan
Pass todata
,If the duration of the transmission is more than 3 seconds, the second item will be executedcase
Statement
quit
var shouldQuit=make(chan struct{}) fun main(){ { //loop } //...out of the loop select { case <-: cleanUp() return default: } //... } //In another coroutine, if the operation encounters an illegal operation or an unprocessable error, the program will send data to shouldQuit notify that the program stops runningclose(shouldQuit)
We define avarType ofshouldQuit
variableChannels for structuresFirst we open aselectLoop, incase
Call the channel method and return the corresponding value; if it is not satisfied, returndefaultvalue. At the same time, we areAnother coroutineIf we encounterIllegal operation or unprocessable errors, justshouldQuit
The send data notification program stops running
Determine Channel status
ch := make (chan int, 5) //... data:=0 select { case ch <- data: default: }
Sometimes we don't like cache slowing down, soNot conducive to our release of resources, so we can use a simple judgment method to make a judgment: first we open aInt type, channel with length 5, we open aselect
cycle,If the value of the data channel can be received by ch, then the statement is executed, otherwise we candefault statement
conductAbandon dataWait for processing operations
This is the end of this article about a brief analysis of the various usages of Channel in Go. For more relevant content on the usage of Channel in Go, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!