SoFunction
Updated on 2025-03-05

Details of the process control of Golang Tongmai

Preface:

Process control is an important part of the logic direction and execution order of each programming language. Process control can be said to be the "merid" of a language.

The most commonly used process controls in Go areifandfor,andswitchandgotoIt is mainly a structure created to simplify code and reduce duplicate code, and belongs to the process control of the extended class.

1. If else (branch structure)

1.1 Basic writing method for if condition judgment

The format of if condition judgment in Go language is as follows:

if expression1 {
    Branches1
} else if expression2 {
    Branches2
} else{
    Branches3
}

When the result of expression 1 istrueWhen the expression 2 is satisfied, branch 1 is executed, otherwise, branch 2 is executed if it is satisfied. When none is satisfied, branch 3 is executed. ifelse ifandelseThey are all optional and can be selected according to actual needs.

There are some rules regarding the use of if conditional statements:

  • If the conditional expressions after the following do not need to be used (), which is different from some programming languages ​​and also reflects the conciseness of the Go language;
  • Each conditional branch (if orelse) braces are necessary, even if there is only one line of code in the braces (such as examples);
  • If the braces that follow { cannot occupy a single line,else The braces before } cannot occupy a single line, otherwise the compilation will not be passed;
  • existif……elseYou can add multiple conditions to the conditional statementelse if, add more conditional branches.

1.2 Special writing method for if condition judgment

There is also a special way to write if condition judgment, which can beif Add an execution statement before the expression, and then make judgments based on the variable value:

func main() {
    if i:=6; i >10 {
        ("i>10")
    } else if  i>5 && i<=10 {
        ("5<i<=10")
    } else {
        ("i<=5")
    }
}

2. for (loop structure)

All loop types in the Go language can be done using the for keyword.

The basic format of the for loop is as follows:

for Initial statement;Conditional expression;Update statement{
    Loop body statement
}

Conditional expression returnstrueThe loop body keeps looping until the conditional expression returnsfalseautomatically exits the loop.

func forDemo() {
 for i := 0; i < 10; i++ {
  (i)
 }
}

forThe initial statement of the loop can be ignored, but the semicolon after the initial statement must be written, for example:

func forDemo2() {
 i := 0
 for ; i < 10; i++ {
  (i)
 }
}

Both the initial statement and the end statement of the for loop can be omitted, for example:

func forDemo3() {
 i := 0
 for i < 10 {
  (i)
  i++
 }
}

This writing is similar to that in other programming languageswhile,existwhileThen add a conditional expression, and the loop continues when the conditional expression is satisfied, otherwise the loop will end.

2.1 Infinite Loop

for {
    Loop body statement
}

forThe loop can passbreakgotoreturnpanicThe statement forces the loop to exit.

existGo In the language, it is also supportedcontinuebreak controlfor cycle:

continue You can jump out of this loop and continue to execute the next loop.

break Can jump out of the wholefor loop, even if the for loop is not executed, it will be terminated forcibly.

3. for range (key value loop)

Can be used in Gofor rangeIterate through arrays, slices, strings,map and channel (channel)。

passfor rangeThere are the following rules for the return value of the traversal:

  • Arrays, slices, strings return indexes and values.
  • mapReturns keys and values.
  • aisle(channel) Returns only the value in the channel.

Notice:

Unlike for, range creates a copy of each iteration value. Therefore, if the value memory usage of each iteration is very small, there is almost no difference in performance between for and range, but if the value memory usage of each iteration is very large, the gap in this case is very obvious.

A simple example shows that when range iteration, the copy is returned.

persons := []struct{ no int }{{no: 1}, {no: 2}, {no: 3}}
for _, s := range persons {
     += 10
}
for i := 0; i < len(persons); i++ {
    persons[i].no += 100
}
(persons) // [{101} {102} {103}]

  • persons is a slice of length 3, each element is a structure.
  • userange When iterating, attempting to increase the no field of each structure by 10, but the modification is invalid becauserange The returned copy.
  • When using for iteration, increase the no field of each structure by 100, and the modification is valid

range What is returned during the iteration process is a copy of the iteration value. If the memory usage of the elements in each iteration is very low, then for andrange The performance is almost the same, such as []int. But if the iterated element takes up a lot of memory, for example, astruct Structure, thenfor The performance will be significantly higher than that ofrange, sometimes there are even thousands of times the performance difference. For this scenario, it is recommended to use for, ifrange, It is recommended to iterate only the subscript and access the iterative value through the subscript. There is no difference between this usage and for. If you want to userange Iterate over the subscript and value at the same time, you need to change the elements of the slice/array to pointers to not affect performance.

4、switch case

useswitchStatements can easily make conditional judgments on a large number of values.

func switchDemo1() {
 finger := 3
 switch finger {
 case 1:
  ("Thumbs up")
 case 2:
  ("index finger")
 case 3:
  ("Middle Finger")
 case 4:
  ("Ring Finger")
 case 5:
  ("Little Finger")
 default:
  ("Invalid input!")
 }
}

Go language specifies eachswitchThere can only be onedefaultBranch.

A branch can have multiple values, multiplecaseValues ​​are separated by English commas.

func testSwitch3() {
 switch n := 7; n {
 case 1, 3, 5, 7, 9:
  ("odd number")
 case 2, 4, 6, 8:
  ("even")
 default:
  (n)
 }
}

The branch can also use expressions, and at this time, there is no need to judge variables after the switch statement:

func switchDemo4() {
 age := 30
 switch {
 case age &lt; 25:
  ("Study hard")
 case age &gt; 25 &amp;&amp; age &lt; 35:
  ("Work well")
 case age &gt; 60:
  ("Enjoy it")
 default:
  ("It's great to be alive")
 }
}

In Go,switch ofcase Just make judgments from top to bottom. Once the conditions are met, the corresponding branch will be executed immediately and returned, and the remaining branches will no longer make judgments. In other words, the switch for Go language is by default, case finally comes with break. This is different from other programming languages. For example, C language must have clear details in the case branch.break Only then can you exit a case. This design of Go language is to prevent forgetting to writebreak When the next onecase Been executed.

fallthroughThe syntax can execute the next case of a case that meets the condition, and is compatible with C language.caseDesigned.

func switchDemo5() {
 s := "a"
 switch {
 case s == "a":
  ("a")
  fallthrough
 case s == "b":
  ("b")
 case s == "c":
  ("c")
 default:
  ("...")
 }
}

Output:

a
b

5. goto (jump to the specified tag)

gotoStatements are unconditional jumps between codes through tags. The goto statement can be helpful in quickly jumping out of loops and avoiding repeated exits. Used in GogotoStatements can simplify the implementation process of some code.

 For example, when a double-layer nested for loop is about to exit:

func gotoDemo1() {
 var breakFlag bool
 for i := 0; i &lt; 10; i++ {
  for j := 0; j &lt; 10; j++ {
   if j == 2 {
    // Set the exit tag    breakFlag = true
    break
   }
   ("%v-%v\n", i, j)
  }
  // Outer for loop judgment  if breakFlag {
   break
  }
 }
}

Using goto statements can simplify the code:

func gotoDemo2() {
 for i := 0; i &lt; 10; i++ {
  for j := 0; j &lt; 10; j++ {
   if j == 2 {
    // Set the exit tag    goto breakTag
   }
   ("%v-%v\n", i, j)
  }
 }
 return
 // LabelbreakTag:
 ("End for loop")
}

6. Break(Breaking out of the loop)

breakThe statement can endforswitchandselectblock of code.

breakThe statement can also add a tag after the statement to indicate that the code block corresponding to a certain tag must be defined in the corresponding tag.forswitchandselecton the code block.For example:

func breakDemo1() {
BREAKDEMO1:
 for i := 0; i < 10; i++ {
  for j := 0; j < 10; j++ {
   if j == 2 {
    break BREAKDEMO1
   }
   ("%v-%v\n", i, j)
  }
 }
 ("...")
}

7. Continue (continue the next loop)

continueThe statement can end the current loop and start the next loop iteration process, and is only used in the for loop.

existcontinueWhen adding a tag after a statement, it means that the loop corresponding to the tag starts.For example:

func continueDemo() {
forloop1:
 for i := 0; i < 5; i++ {
  // forloop2:
  for j := 0; j < 5; j++ {
   if i == 2 && j == 2 {
    continue forloop1
   }
   ("%v-%v\n", i, j)
  }
 }
}

This is the article about the detailed process control of Golang Tongmai. For more information about Golang Tongmai, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!