Go语言学习笔记-流程控制语句

流程控制语句

1. if

if 5 > 9 {
    fmt.Println("5>9")
}
  • 如果逻辑表达式成立,就会执行{}里的内容。
  • 逻辑表达式不需要加()。
  • "{"必须紧跟在逻辑表达式后面,不能另起一行。
if c, d, e := 5, 9, 2; c < d && (c > e || c > 3) { //初始化多个局部变量。复杂的逻辑表达式
    fmt.Println("fit")
}
  • 逻辑表达中可以含有变量或常量。
  • if句子中允许包含1个(仅1个)分号,在分号前初始化一些局部变量(即只在if块内可见)。

if-else的用法

color := "black"
if color == "red" { //if只能有一个
    fmt.Println("stop")
} else if color == "green" {
    fmt.Println("go")
} else if color == "yellow" { //else if可以有0个、一个或者连续多个
    fmt.Println("stop")
} else { //else有0个或1个
    fmt.Printf("invalid traffic signal: %s\n", strings.ToUpper(color))
}

if表达式嵌套

if xxx {
    if xxx {
    }else if xxx{
    }else{
    }
}else{
    if xxx {
    }else{
    }
}

  注意太深的嵌套不利于代码的维护,比如

if (true) {
    if (true) {
        if (true) {
            if (true) {
                if (true) {
                }
            }
        }
    }
}
if.go

package main

import "fmt"

func ifnext() int {
	a, b, c, d, e := 1, 2, 3, 4, 5

	if a > b && (a > d || d < e) {

	}

	if a > b {
		if b > c {
			if c < d {
				if d > e {
					return 100
				}
			}
		}
	}
	return 0
}

func ifnext2() int {
	a, b, c, d, e := 1, 2, 3, 4, 5
	if a <= b {
		return 0
	}
	if b <= c {
		return 0
	}
	if c >= d {
		return 0
	}
	if d <= e {
		return 0
	}
	return 100
}

func testif() {
	if a := 9; a%2 == 0 {
		fmt.Println("a是一个偶数")
	} else {
		fmt.Println("a是一个奇数")
	}

	m := map[string]int{"语文": 59, "英语": 0}
	fmt.Println(m["数学"])
	if v, exists := m["数学"]; exists { //v和exists是【if块】的局部变量,【if块】包含了else
		fmt.Println(v)
	} else if 3 > 6 {
		fmt.Println(v, exists)
	} else {
		fmt.Println(v, exists)
	}

}
func main() {
	ifnext()
	ifnext2()
	testif()
}



2. switch

color := "black"
switch color {
case "green" :	//相当于  if color== "green"
	fmt.Println("go")
case "red" :		//相当于else if color== "red" 
	fmt.Println("stop")
default:		 //相当于else 
	fmt.Printf("invalid traffic signal: %s\n", strings.ToUpper(color))
}
  • switch-case-default可能模拟if-else if-else,但只能实现相等判断。
  • switch和case后面可以跟常量、变量或函数表达式,只要它们表示的数据类型相同就行。
  • case后面可以跟多个值,只要有一个值满足就行。
func add(a int) int {
	return a + 10
}

func switch_expression() {
	var a int = 5
	switch add(a) { //switch后跟一个函数表达式
	case 15: //case后跟一个常量
		fmt.Println("right")
	default:
		fmt.Println("wrong")
	}

	const B = 15
	switch B { //switch后跟一个常量
	case add(a): //case后跟一个函数表达式
		fmt.Println("right")
	default:
		fmt.Println("wrong")
	}
}

空switch

  switch后带表达式时,switch-case只能模拟相等的情况;如果switch后不带表达式,case后就可以跟任意的条件表达式。

func switch_condition() {
	color := "yellow"
	switch color {
	case "green":
		fmt.Println("go")
	case "red", "yellow": //用逗号分隔多个condition,它们之间是“或”的关系,只需要有一个condition满足就行
		fmt.Println("stop")
	}

	//switch后带表达式时,switch-case只能模拟相等的情况;如果switch后不带表达式,case后就可以跟任意的条件表达式
	switch {
	case add(5) > 10:
		fmt.Println("right")
	default:
		fmt.Println("wrong")
	}
}

switch Type

func switch_type() {
	var num interface{} = 6.5
	switch num.(type) { //获取interface的具体类型。.(type)只能用在switch后面
	case int:
		fmt.Println("int")
	case float32:
		fmt.Println("float32")
	case float64:
		fmt.Println("float64")
	case byte:
		fmt.Println("byte")
	default:
		fmt.Println("neither")
	}

	switch value := num.(type) { //相当于在每个case内部申明了一个变量value
	case int: //value已被转换为int类型
		fmt.Printf("number is int %d\n", value)
	case float64: //value已被转换为float64类型
		fmt.Printf("number is float64 %f\n", value)
	case byte, string: //如果case后有多个类型,则value还是interface{}类型
		fmt.Printf("number is inerface %v\n", value)
	default:
		fmt.Println("neither")
	}

	//等价形式
	switch num.(type) {
	case int:
		value := num.(int)
		fmt.Printf("number is int %d\n", value)
	case float64:
		value := num.(float64)
		fmt.Printf("number is float64 %f\n", value)
	case byte:
		value := num.(byte)
		fmt.Printf("number is byte %d\n", value)
	default:
		fmt.Println("neither")
	}
}

fallthrough

  • 从上往下,只要找到成立的case,就不再执行后面的case了。所以为提高性能,把大概率会满足的情况往前放
  • case里如果带了fallthrough,则执行完本case还会去判断下一个case是否满足
  • 在switch type语句的case子句中不能使用fallthrough
func fall_throth(age int) {
	fmt.Printf("您的年龄是%d, 您可以:\n", age)
	switch {
	case age > 50:
		fmt.Println("出任国家首脑")
		fallthrough
	case age > 25:
		fmt.Println("生育子女")
		fallthrough
	case age > 22:
		fmt.Println("结婚")
		fallthrough
	case age > 18:
		fmt.Println("开车")
		fallthrough
	case age > 16:
		fmt.Println("参加工作")
	case age > 15:
		fmt.Println("上高中")
		fallthrough
	case age > 3:
		fmt.Println("上幼儿园")
	}
}
switch.go

package main

import "fmt"

func ffff() int {
	return 345
}

func testSwitch1() {
	a := 345
	switch a {
	case ffff():
		fmt.Println("a的值等于函数ffff()的返回值")
	case 3:
		var b int
		b = 9
		fmt.Println(a + b)
	case 7:
		fmt.Println(7)
	case 10, 34, 345:
		fmt.Println("a是10,34,345其中一个")
	default:
		fmt.Println("以上3个case都没有命中")
	}

}

func testSwitch2() {
	switch {
	case 2 > 4 || 5 < 9:
		fmt.Println("fdferfe")
	case "dff" == "dff":
		fmt.Println("4564")
	default:
		fmt.Println("ok")
	}
}

type A struct {
	Gender byte //1:男   2:女   0:未知
}

func testSwitch3() {
	var num interface{} //interface{}是一种数据类型   object
	num = 3212
	num = "32432"
	num = true
	//num = A{}
	switch v := num.(type) { //.(type)获取具体的类型
	case int:
		fmt.Println(v + 100)
	case float32, float64:
		fmt.Printf("%f\n", v)
	case byte, string, bool:
		fmt.Printf("%v\n", v)
	default:
		fmt.Println("以上3个case都没有命中")
	}
}

func testSwitch4(a A) {
	switch a.Gender {
	case 2:
		fmt.Println("该学员是女生")
	case 1:
		fmt.Println("该学员是男生")
		fallthrough
	case 0:
		fmt.Println("该学员性别未知")
	case 4:
		fmt.Printf("ok")
	}
}

func main() {
	//testSwitch1()
	//testSwitch2()
	//testSwitch3()
	student := A{Gender: 1}
	testSwitch4(student)
}

3. for

arr := []int{1, 2, 3, 4, 5}
for i := 0; i < len(arr); i++ { //正序遍历切片
	fmt.Printf("%d: %d\n", i, arr[i])
}

for 初始化局部变量;条件表达式;后续操作

for sum, i := 0, 0; i < len(arr) && sum < 100; sum, i = sum*1, i+1
  • 局部变量指仅在for块内可见。
  • 初始化变量可以放在for上面。
  • 后续操作可以放在for块内部。
  • 只有条件判断时,前后的分号可以不要。
  • for{}是一个无限循环。

for range

  • 遍历数组或切片
    • for i, ele := range arr
  • 遍历string
    • for i, ele := range “我会唱ABC” //ele是rune类型
  • 遍历map,go不保证遍历的顺序
    • for key, value := range m
  • 遍历channel,遍历前一定要先close
    • for ele := range ch
  • for range拿到的是数据的拷贝

for嵌套
  矩阵乘法需要用到三层for循环嵌套。
在这里插入图片描述

func nest_for() {
	const SIZE = 4

	A := [SIZE][SIZE]float64{}
	//初始化二维数组
	//两层for循环嵌套
	for i := 0; i < SIZE; i++ {
		for j := 0; j < SIZE; j++ {
			A[i][j] = rand.Float64() //[0,1)上的随机数
		}
	}

	B := [SIZE][SIZE]float64{}
	for i := 0; i < SIZE; i++ {
		for j := 0; j < SIZE; j++ {
			B[i][j] = rand.Float64() //[0,1)上的随机数
		}
	}

	rect := [SIZE][SIZE]float64{}
	//三层for循环嵌套
	for i := 0; i < SIZE; i++ {
		for j := 0; j < SIZE; j++ {
			prod := 0.0
			for k := 0; k < SIZE; k++ {
				prod += A[i][k] * B[k][j]
			}
			rect[i][j] = prod
		}
	}

	i, j := 2, 1
	fmt.Println(A[i]) //二维数组第i行
	//打印二维数组的第j列
	//注意:B[:][j]这不是二维数组第j列,这是二维数组第j行!
	for _, row := range B {
		fmt.Printf("%g ", row[j])
	}
	fmt.Println()
	fmt.Println(rect[i][j])
}
for.go

package main

import (
	"fmt"
	"math/rand"
)

func matrixMultiply(A [4][4]float32, B [4][4]float32) [4][4]float32 {
	C := [4][4]float32{}
	for i := 0; i < 4; i++ {
		for j := 0; j < 4; j++ {
			//C[i][j]是A的第i行和B的第j列的向量内积
			//i=0 j=0
			var sum float32 = 0.0 //sum是A的第i行和B的第j列的向量内积
			for k := 0; k < 4; k++ {
				sum += A[i][k] * B[k][j]
			}
			C[i][j] = sum
		}
	}
	return C
}

func initMatric(A *[4][4]float32) {
	for i := 0; i < 4; i++ {
		for j := 0; j < 4; j++ {
			A[i][j] = rand.Float32()
		}
	}
}

func main() {
	//arr := []int{1, 2, 3, 4, 5}
	//var sum int
	//var i int
	for sum, i = 0, 0; i < len(arr); sum, i = sum+arr[i], i+1 {
		fmt.Println(sum)
	}
	//
	//for {
	//	if i < len(arr) {
	//		sum += arr[i]
	//		i++
	//	} else {
	//		break
	//	}
	//}
	//
	//fmt.Println(sum)
	var A [4][4]float32
	var B [4][4]float32

	initMatric(&A)
	initMatric(&B)

	C := matrixMultiply(A, B)
	for i := 0; i < 4; i++ {
		for j := 0; j < 4; j++ {
			fmt.Printf("%.4f  ", C[i][j])
		}
		fmt.Println()
	}
}

4. break与continue

  • break与continue用于控制for循环的代码流程,并且只针对最靠近自己的外层for循环。
  • break:退出for循环,且本轮break下面的代码不再执行。
  • continue:本轮continue下面的代码不再执行,进入for循环的下一轮。
//break和continue都是针对for循环的,不针对if或switch
//break和continue都是针对套在自己外面的最靠里的那层for循环,不针对更外层的for循环(除非使用Label)
func complex_break_continue() {
	const SIZE = 5
	arr := [SIZE][SIZE]int{}
	for i := 0; i < SIZE; i++ {
		fmt.Printf("开始检查第%d行\n", i)
		if i%2 == 1 {
			for j := 0; j < SIZE; j++ {
				fmt.Printf("开始检查第%d列\n", j)
				if arr[i][j]%2 == 0 {
					continue //针对第二层for循环
				}
				fmt.Printf("将要检查第%d列\n", j+1)
			}
			break //针对第一层for循环
		}
	}
}
bc.go

package main

import "fmt"

func main() {
	//break
	//sum := 0
	//for i := 0; i < 5; i++ {
	//	if i == 3 {
	//		break
	//	}
	//	fmt.Printf("i=%d\n", i)
	//	sum += i
	//}
	//fmt.Println(sum)
	//i=0
	//i=1
	//i=2
	//3

	//continue
	//sum := 0
	//for i := 0; i < 5; i++ {
	//	if i == 3 {
	//		continue
	//	}
	//	fmt.Printf("i=%d\n", i)
	//	sum += i
	//}
	//fmt.Println(sum)
	//i=0
	//i=1
	//i=2
	//i=4
	//7

	sum := 0
	n := 5
	for k := 0; k < n; k++ {//3*4
		if k == 2 {
			continue
		}
		for i := 0; i < n; i++ { //3*5
			if i == 3 {
				break
			}
			fmt.Printf("i=%d\n", i)
			sum += i
		}
		fmt.Println(sum) //30
	}
}

5. goto与Label

var i int = 4
MY_LABEL:
	i += 3
	fmt.Println(i)
     goto MY_LABEL //返回定义MY_LABEL的那一行,把代码再执行一遍(会进入一个无限循环)
if i%2 == 0 {
	goto L1 //Label指示的是某一行代码,并没有圈定一个代码块,所以goto L1也会执行L2后的代码
} else {
	goto L2//先使用Label
}
L1: 
	i += 3
L2: //后定义Label。Label定义后必须在代码的某个地方被使用
	i *= 3

退出for循环
  goto与Label结合可以实现break的功能,甚至比break更强大。

for i := 0; i < SIZE; i++ {
L2:
for j := 0; j < SIZE; j++ {
	goto L1
}
}
L1:
xxx

break、continue与Label

  • break、continue与Label结合使用可以跳转到更外层的for循环。
  • continue和break针对的Label必须写在for前面,而goto可以针对任意位置的Label。
func break_label() {
	const SIZE = 5
	arr := [SIZE][SIZE]int{}
L1:
	for i := 0; i < SIZE; i++ {
	L2:
		fmt.Printf("开始检查第%d行\n", i)

		if i%2 == 1 {
		L3:
			for j := 0; j < SIZE; j++ {
				fmt.Printf("开始检查第%d列\n", j)
				if arr[i][j]%3 == 0 {
					break L1 //直接退出最外层的fot循环
				} else if arr[i][j]%3 == 1 {
					goto L2 //continue和break针对的Label必须写在for前面,而goto可以针对任意位置的Label
				} else {
					break L3
				}
			}
		}
	}
}
lb.go

package main

import "fmt"

//func testGoto() {
//	var i = 5
//L1:
//	i += 3 //8
//	i *= 2 //16
//	fmt.Println(i)
//	if i > 200 {
//		fmt.Println("OVER")
//		return
//	}
//	goto L1
//}
//
Label只是行号的标记
//func if_goto() {
//	i := 5
//	if i%2 == 0 {
//		goto L1 //直接跳到27行去执行
//	} else {
//		goto L2
//	}
//	fmt.Println("我不会被执行")
//L1:
//	i += 3
//	fmt.Println(i) //7
//L2:
//	i *= 2
//	fmt.Println(i) //14
//}

func for_goto() {
	const SIZE = 5
	arr := [SIZE][SIZE]int{}
L1:
	for i := 0; i < SIZE; i++ {
	L2:
		fmt.Printf("开始检查第%d行\n", i)
	L3:
		if i%2 == 1 {
			for j := 0; j < SIZE; j++ {
				fmt.Printf("开始检查第%d列\n", j)
				if arr[i][j]%3 == 0 {
					goto L1 //死循环
					//continue L1  //输出7行结果
					//break L1     //输出3行结果
				} else if arr[i][j]%3 == 1 {
					goto L2
				} else {
					goto L3
				}
			}
		}
	}
}

func main() {
	//testGoto()
	//if_goto()
	for_goto()
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值