SoFunction
Updated on 2025-03-05

A brief analysis of the various usages of Channel in Go language

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 conditionsAnd 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;ifIn the boolean expressiontruehour,The following statement block executes, iffalseThen executeelseStatement 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 languagemiddle,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, weifNested 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 itSwitchStatement

Switch definition

switchStatements are used to perform different actions based on different conditions, eachcaseThe branches are unique, tested one by one from top to bottom until they match.Golang switchBranch 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,rightmarksconductSwitchJudgment operation, whencaseWhen different values ​​are met, the values ​​printed by calling the function are also different.

Type Switch

switchStatements can also be used fortype-switchTo 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 SwitchThere 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

  • selectThe statement is similar toswitchstatement, butselectA runnable will be executed randomlycase. If notcaseCan be run,It will block, until there iscaseCan be run.
  • selectyesGoOne control structure in the same way as theswitchStatement. EachcaseMust be a communication operation, either send or receive
  • select Randomly execute a runnablecase. If notcaseCan be run,It will block, until there iscaseCan 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

  • EachcaseAllMust be a communication
  • allchannelExpressions 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 multiplecaseAll can be run, Select will randomly and fairly select an execution. Others will not be executed.
  • If there isdefaultclause, execute the statement.
  • If notdefaultWords,selectWillblock, until a certain communication can be run;GoWill not be corrected againchannelThe 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、c3Three variables, and usechanaisle.Explanation of writing: One can be sentintType of datachannelGenerally written aschan int, according to the grammar rules above: if there isdefaultThe clause is executed, so the code execution code above is:no communication

Select Usage Supplement

  • We can useselectCome and listenchannelData flow
  • selectUsage andswitchThe syntax is very similar,selectStart a new selection block, each selection condition iscaseStatement to describe
  • switchStatementAny comparison condition can be selected using equal comparisonselectThere are many restrictions, the biggest one is eachcaseThere must be one in the statementIO operation
  • If eachcaseNone of them are read,Go languageWill be read automaticallydefaultWhat the statement describes,Under normal circumstances, eachselectThe program will have an output statement
  • If neithercaseThe statement satisfies it, and it does not existdefaultstatement,The program enters a blocking stateThe 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 aselectStatement, in the firstcaseInside, we willresChanPass todataIf the duration of the transmission is more than 3 seconds, the second item will be executedcaseStatement

quit

var shouldQuit=make(chan struct{})
fun main(){
    {
        //loop
    }
    //...out of the loop
    select {
        case &lt;-:
            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 ofshouldQuitvariableChannels for structuresFirst we open aselectLoop, incaseCall 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, justshouldQuitThe 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 aselectcycle,If the value of the data channel can be received by ch, then the statement is executed, otherwise we candefault statementconductAbandon 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!