Home  >  Article  >  Backend Development  >  An article briefly analyzing process control in Golang

An article briefly analyzing process control in Golang

青灯夜游
青灯夜游forward
2022-11-25 21:07:206271browse

This article will teach you about Golang and talk about process control in the basics of Go language. I hope it will be helpful to you.

An article briefly analyzing process control in Golang

Flow control based on Go language mainly includes the following contents:

  • Conditional statement if
  • Conditional statement switch
  • Conditional statement select
  • Loop statement for
  • Loop statement range
  • Loop control Goto, Break, Continue

[Programming tutorial recommendation :Programming Teaching

1. Conditional statement if

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

if 表达式1 {
    分支1
} else if 表达式2 {
    分支2
} else{
    分支3
}

Front-end students must be relatively familiar with js. Compared with js, go expressions remove the brackets (), but at the same time give some constraints, and ifThe matching left bracket { must be placed on the same line as if and expression . Placing { elsewhere will trigger a compilation error. . In the same way, { that matches else must also be written on the same line as else, and else must also be written on the same line as the previous if or else if The curly braces on the right are on the same line.

x := 0

// if x > 10        // Error: missing condition in if statement
// {
// }

if n := "abc"; x > 0 {     // 初始化语句未必就是定义变量, 如 println("init") 也是可以的。
    println(n[2])
} else if x < 0 {    // 注意 else if 和 else 左大括号位置。
    println(n[1])
} else {
    println(n[0])
}



 *不支持三元操作符(三目运算符) "a > b ? a : b"。
 
package main

import "fmt"

func main() {
   /* 定义局部变量 */
   var a int = 10
   /* 使用 if 语句判断布尔表达式 */
   if a < 20 {
       /* 如果条件为 true 则执行以下语句 */
       fmt.Printf("a 小于 20\n" )
   }
   fmt.Printf("a 的值为 : %d\n", a)
}


以上代码执行结果为:
a 小于 20
a 的值为 : 10

2. Conditional statement switch

The switch statement is used to perform different actions based on different conditions. Each case branch is unique. Test them one by one from top to bottom until they match. Golang switch branch expression can be of any type, not limited to constants. break can be omitted and terminates automatically by default.

package main

import "fmt"

func main() {
   /* 定义局部变量 */
   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" :
         fmt.Printf("优秀!\n" )     
      case grade == "B", grade == "C" :
         fmt.Printf("良好\n" )      
      case grade == "D" :
         fmt.Printf("及格\n" )      
      case grade == "F":
         fmt.Printf("不及格\n" )
      default:
         fmt.Printf("差\n" )
   }
   fmt.Printf("你的等级是 %s\n", grade )
}



以上代码执行结果为:
优秀!
你的等级是 A

3. Conditional statement select

The select statement is similar to the switch statement, but select will randomly execute a runnable case. If there is no case to run, it will block until there is a case to run.

select is a control structure in Go, similar to the switch statement used for communication. Each case must be a communication operation, either sending or receiving. select randomly executes a runnable case. If there is no case to run, it will block until there is a case to run. A default clause should always be runnable.

The following describes the syntax of the select statement:

    每个case都必须是一个通信
    所有channel表达式都会被求值
    所有被发送的表达式都会被求值
    如果任意某个通信可以进行,它就执行;其他被忽略。
    如果有多个case都可以运行,Select会随机公平地选出一个执行。其他不会执行。
    否则:
    如果有default子句,则执行该语句。
    如果没有default字句,select将阻塞,直到某个通信可以运行;Go不会重新对channel或值进行求值。
package main

import "fmt"

func main() {
   var c1, c2, c3 chan int
   var i1, i2 int
   select {
      case i1 = <-c1:
         fmt.Printf("received ", i1, " from c1\n")
      case c2 <- i2:
         fmt.Printf("sent ", i2, " to c2\n")
      case i3, ok := (<-c3):  // same as: i3, ok := <-c3
         if ok {
            fmt.Printf("received ", i3, " from c3\n")
         } else {
            fmt.Printf("c3 is closed\n")
         }
      default:
         fmt.Printf("no communication\n")
   }    
}



以上代码执行结果为:

 no communication

select can monitor the data flow of the channel

The usage of select is very similar to the switch syntax. A new one starts with select In the selection block, each selection condition is described by a case statement.

Compared with the switch statement that can select any condition that uses equality comparison, select has many restrictions. The biggest restriction is that in each case statement Must be an IO operation

 select { //不停的在这里检测
    case <-chanl : //检测有没有数据可以读
    //如果chanl成功读取到数据,则进行该case处理语句
    case chan2 <- 1 : //检测有没有可以写
    //如果成功向chan2写入数据,则进行该case处理语句


    //假如没有default,那么在以上两个条件都不成立的情况下,就会在此阻塞//一般default会不写在里面,select中的default子句总是可运行的,因为会很消耗CPU资源
    default:
    //如果以上都没有符合条件,那么则进行default处理流程
    }

In a select statement, Go will evaluate each send and receive statement in sequence from beginning to end.

If any one of the statements can continue to execute (that is, it is not blocked), then choose any one of those statements that can be executed to use. If no statement can be executed (that is, all channels are blocked), then there are two possible situations: ① If the default statement is given, the default process will be executed, and the execution of the program will start from after the select statement. statement. ② If there is no default statement, the select statement will be blocked until at least one case can proceed.

Typical usage - timeout judgment

//比如在下面的场景中,使用全局resChan来接受response,如果时间超过3S,resChan中还没有数据返回,则第二条case将执行
var resChan = make(chan int)
// do request
func test() {
   select {
   case data := <-resChan:
       doData(data)
   case <-time.After(time.Second * 3):
       fmt.Println("request time out")
   }
}

func doData(data int) {
   //...
}

4. The loop statement for

is the same as if , compared to js, ​​the for loop of go language also removes the brackets (), and there is not much difference in other aspects.

package main

import "fmt"

func main() {

   var b int = 15
   var a int

   numbers := [6]int{1, 2, 3, 5}

   /* for 循环 */
   for a := 0; a < 10; a++ {
      fmt.Printf("a 的值为: %d\n", a)
   }

   for a < b {
      a++
      fmt.Printf("a 的值为: %d\n", a)
      }

   for i,x:= range numbers {
      fmt.Printf("第 %d 位 x 的值 = %d\n", i,x)
   }   
}


以上实例运行输出结果为:

    a 的值为: 0
    a 的值为: 1
    a 的值为: 2
    a 的值为: 3
    a 的值为: 4
    a 的值为: 5
    a 的值为: 6
    a 的值为: 7
    a 的值为: 8
    a 的值为: 9
    a 的值为: 1
    a 的值为: 2
    a 的值为: 3
    a 的值为: 4
    a 的值为: 5
    a 的值为: 6
    a 的值为: 7
    a 的值为: 8
    a 的值为: 9
    a 的值为: 10
    a 的值为: 11
    a 的值为: 12
    a 的值为: 13
    a 的值为: 14
    a 的值为: 15
    第 0 位 x 的值 = 1
    第 1 位 x 的值 = 2
    第 2 位 x 的值 = 3
    第 3 位 x 的值 = 5
    第 4 位 x 的值 = 0
    第 5 位 x 的值 = 0

5. The loop statement range

Golang range is similar to the iterator operation, returning (index, value) or (key, value).

The range format of for loop can iterate over slices, maps, arrays, strings, etc. The format is as follows:

for key, value := range oldMap {
    newMap[key] = value
}
package main

func main() {
    s := "abc"
    // 忽略 2nd value,支持 string/array/slice/map。
    for i := range s {
        println(s[i])
    }
    // 忽略 index。
    for _, c := range s {
        println(c)
    }
    // 忽略全部返回值,仅迭代。
    for range s {

    }

    m := map[string]int{"a": 1, "b": 2}
    // 返回 (key, value)。
    for k, v := range m {
        println(k, v)
    }
}

输出结果:

    97
    98
    99
    97
    98
    99
    a 1
    b 2

What is the difference between for and for range?

The main reason is that the usage scenarios are different

for can traverse arrays and slices, and traverse maps whose keys are integer increments. , traversing string

for range can do all the things that for can do, but it can do what for cannot do, including traversing a map whose key is string type and getting the key and value at the same time, traversing channel

6. Loop control Goto, Break, Continue

Loop control statements

Loop control statements can control the execution process of statements within the loop body.

GO language supports the following loop control statements:

Goto, Break, Continue

    1.三个语句都可以配合标签(label)使用
    2.标签名区分大小写,定以后若不使用会造成编译错误
    3.continue、break配合标签(label)可用于多层循环跳出
    4.goto是调整执行位置,与continue、break配合标签(label)的结果并不相同

break(break out of the loop): The continue (continue the next cycle) break statement can end the code blocks of for, switch and select. The break statement can also add a label after the statement to indicate exiting the code block corresponding to a certain label. The label requirements must be defined in the corresponding for, switch and select code block.

continue(继续下次循环)continue语句可以结束当前循环,开始下一次的循环迭代过程,仅限在for循环内使用。在 continue语句后添加标签时,表示开始标签对应的循环

goto语句通过标签进行代码间的无条件跳转。goto语句可以在快速跳出循环、避免重复退出上有一定的帮助。Go语言中使用goto语句能简化一些代码的实现过程。 例如双层嵌套的for循环要退出时:

func gotoDemo1() {
	var breakFlag bool
	for i := 0; i < 10; i++ {
		for j := 0; j < 10; j++ {
			if j == 2 {
				// 设置退出标签
				breakFlag = true
				break
			}
			fmt.Printf("%v-%v\n", i, j)
		}
		// 外层for循环判断
		if breakFlag {
			break
		}
	}
}

使用goto语句能简化代码:

func gotoDemo2() {
	for i := 0; i < 10; i++ {
		for j := 0; j < 10; j++ {
			if j == 2 {
				// 设置退出标签
				goto breakTag
			}
			fmt.Printf("%v-%v\n", i, j)
		}
	}
	return
	// 标签
breakTag:
	fmt.Println("结束for循环")
}

结束:

再次提醒,需要进技术交流群的同学,可以加我微信fangdongdong_25,需要进前端工程师交流群的备注“前端”,需要进go后端交流群的备注“go后端”

【相关推荐:Go视频教程

The above is the detailed content of An article briefly analyzing process control in Golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete