go process control


  • if conditional statements in Go do not need parentheses. A variable can be declared in conditional statements. Any variable declared here can be used in all conditional branches.

    if x := 11; x > 10 {
      fmt.Println("x is greater than 10")
    } else {
      fmt.Println("x is less than 10")


  • Use goto to jump to a tag that must be defined within the current function. The tag name is case sensitive.

    func myFunc() {
      i := 0
      Here:   //The first word in this line, ending with a colon
      goto Here   //Jump to Here


  • for is the only circular structure in go. There are several ways to use it in go

    //Classic initialization / condition / subsequent for loop
    for expression1; expression2; expression3 {}
    //With a single loop condition, expression1 and expression3 are ignored:
    sum := 1
    for ; sum < 1000;  {
      sum += sum
    //Among them, you can also omit it, so it becomes the following code, which is the function of while.
    for sum < 1000 {}
    //The for loop without conditions will be executed until break or return is used in the loop body to jump out of the loop    
    for {

break and continue

  • When the nesting depth is too deep, break can be used with the label, that is, jump to the position specified by the label, and break and continue can also follow the label to jump to the outer loop in multiple loops

for with range can be used to read slice, map and array data

  • range also provides the index and value of each item in the array and slice. We don't need to use the null value definer when we need to index, because the compiler will report an error for a declared but not called variable. Sometimes we need this index.

  • range iterates key value pairs in map


switch sExpr {
  case expr1:
  some instructions
  case expr2:
  some other instructions
  other code

switch i {
  case 2, 3, 4://We put a lot of values together in a case
  fmt.Println("i is equal to 2, 3 or 4")
  fmt.Println("All I know is that i is an integer")

//If a switch has no expression, it matches true
//switch without expression is another way of if/else
switch {
  case t.Hour() < 12:
  fmt.Println("it's before noon")
  fmt.Println("it's after noon")

//In Go, the switch is equivalent to the break at the end of each case by default,
//After the match is successful, it will not automatically execute other case s down, but jump out of the whole switch, 
//But you can use fallthrough to enforce the following case code. * *

integer := 6
switch integer {
  case 6:
  fmt.Println("The integer was <= 6")
  fmt.Println("default case")
//The integer was <= 6
//default case

Tags: Go less

Posted on Tue, 05 Nov 2019 12:28:33 -0500 by poleposters