Golang入门学习(二):控制分支

在这里插入图片描述


1. 控制分支

1.1 if-else分支

基本语法:

	if condition1 {
		代码块1
	}else if condition2 {
		代码块2
	}
	............
	else{
		代码块3
	}
  • if之后的条件不需要添加小括号(官方不需要使用)
  • 分支执行体必须使用{}括起来,否则语法错误
  • 只能执行一个代码块,else部分不是必须的
  • if/elseif 中的condition必须是条件表达式,不能为赋值语句
/*
*	if-else控制语句:
*请输入一个年龄,如果年龄大于18岁,可以进入风月场合;否则不让进入
 */

func main() {
	var age int

	fmt.Println("请输入年龄:")
	fmt.Scanln(&age)

	if age < 18 {
		fmt.Println("少儿不宜,滚犊子!!!")
	} else {
		fmt.Println("大爷,您里面请")
	}

}
  • fmt.Scanln用法参见:https://golang.org/pkg/fmt/

if-else的执行体必须使用{}括起来

func main() {
	var x int = 4

	if x > 2 {
		fmt.Printf("%d > 2\n", x)
	} else {
		fmt.Printf("%d < 2\n", x)
	}

}

1.2 switch分支

基本介绍:

  • 根据匹配不同条件执行不同的动作
  • GO中case分支之后不再需要添加break
  • [ ]

基本语法:

	switch 表达式{
	
	case 表达式1,表达式2,...:
		执行的语句块1
	case 表达式3,表达式4,...:
		执行的语句块2
	...
	default:
		执行的语句块n
	}

快速入门示例:

func main() {
	var key byte

	fmt.Println("请输入任意一个字符:A,B,C,D,E,F,G")
	fmt.Scanf("%c", &key)

	switch key {

	case 'A', 'a':
		fmt.Println("Monday!!!")
	case 'B', 'b':
		fmt.Println("Tuesday!!!")
	case 'C', 'c':
		fmt.Println("Wednesday!!!")
	case 'D', 'd':
		fmt.Println("Thursday!!!")
	case 'E', 'e':
		fmt.Println("Friday!!!")
	case 'F', 'f':
		fmt.Println("Saturday!!!")
	case 'G', 'g':
		fmt.Println("Sunday!!!")
	default:
		fmt.Println("Error!!!")
	}
}

switch 细节讨论:

  • case 之后是一个(多个)表达式(常量、变量、有返回值的函数),witch同样如此
  • 每一个case分支不需要break来结束
  • case后的表达式的值的数据类型必须和switch表达式数据类型保持一致
  • case之后的表达式如果为常量,则不能重复:
  • default语句不是必须的
    func demo1() {
    	var a int = 10
    
    	switch a {
    	case 1, 2, 3:
    		fmt.Println("1111111111111")
    	case 4, 5, 6:
    		fmt.Println("22222222222222")
    	case 7, 7:/*常量重复,无法编译通过*/
    		fmt.Println("3333333333333")
    	}
    }
    
  • switch之后可以不填写表达式,在case时再填写
    	func demo3() {
    	var a int = 10
    
    	switch {
    	case a == 10:
    		fmt.Println("1111111111111")
    	case a == 20:
    		fmt.Println("22222222222222")
    	default:
    		fmt.Println("3333333333333")
    	}
    }
    
  • case之后可以使用范围匹配
    func demo4() {
    	var score int = 91
    
    	switch {
    	case score == 100:
    		fmt.Println("优秀")
    	case score >= 80 && score < 100:
    		fmt.Println("优秀")
    	case score >= 60 && score < 80:
    		fmt.Println("良")
    	default:
    		fmt.Println("差")
    	}
    }
    
  • switch中允许直接声明一个变量,然后以分号结束
    func demo5() {
    	switch age := 15; {
    	case age < 18:
    		fmt.Println(age, "未成年人,小屁孩!!!!")
    	default:
    		fmt.Println("Who care your age!")
    	}
    }
    
  • switch穿透:在case语句块中后添加fallthrough,则会继续执行检测判断后面的case语句
    func demo6() {
    	var score int = 91
    
    	switch {
    	case score == 100:
    		fmt.Println("优秀")
    		fallthrough //默认只能穿透一层
    	case score >= 80 && score < 100:
    		fmt.Println("优秀")
    		fallthrough
    	case score >= 60 && score < 80:
    		fmt.Println("良")
    		fallthrough
    	default:
    		fmt.Println("差")
    	}
    }
    
  • 使用type-switch判断一个空接口指向的变量类型
    func demo7() {
    	var x interface{}
    	x = demo6
    
    	switch i := x.(type) {
    	case nil:
    		fmt.Printf("x的类型为:%T\n", i)
    	case int, int8, int16, int32, int64:
    		fmt.Printf("x的类型为:%T\n", i)
    	case float32, float64:
    		fmt.Printf("x的类型为:%T\n", i)
    	case func(int) float64:
    		fmt.Printf("x的类型为:%T\n", i)
    	case bool, string:
    		fmt.Printf("x的类型为:%T\n", i)
    	default:
    		fmt.Printf("x的类型为:%T\n", i)
    	}
    }
    

0

  • 语法格式:
	for 循环变量初始化;循环条件;循环变量迭代{
		循环体
	}

	for 循环条件{
		循环执行体
	}

	for {/*死循环*/
		循环执行体
	}
  • 快速入门示例:
func main() {
	var i int

	for i = 2000; i < 2021; i++ {
		fmt.Printf("%d年过去了\n", i)
	}

	i = 2000
	for i < 2021 {
		fmt.Printf("%d年过去了\n", i)
		i++
	}

	for {
		fmt.Printf("%d年过去了\n", i)
		i++
		if i > 2020 {
			break
		}
	}
}
  • 字符串遍历方式:
    • for循环遍历
      func demo1() {
      	var str string = "Hello World!"
      
      	for i := 0; i < len(str); i++ {
      		fmt.Printf("str[%d] = %c\n", i, str[i])
      	}
      
      }
      
    • for + range遍历
      func demo2() {
      	var str string = "Hello World!"
      
      	for index, val := range str {
      		fmt.Printf("str[%d] = %q\n", index, val)
      	}
      }
      
  • for细节讨论
    上述遍历过程中,如果包含中文,则遍历会出现乱码的问题。原因是:传统遍历采用utf-8编码(字节遍历),而汉字在utf8中对应3个字节。
    解决方案:

将字符串转换为切片的方式,然后再进行遍历。
对于上面的两种字符串遍历方式,第一种for循环逐字节遍历由于编码问题导致中文乱码;而第二种for-range方式则不会出现此问题:

/*字符串中包含中文字符*/
func demo3() {
	var str string = "Hello World!数风流人物,还看今朝"

	for i := 0; i < len(str); i++ {
		fmt.Printf("str[%d] = %c\n", i, str[i])/*乱码*/
	}
	fmt.Println("")
	for index, val := range str {
		fmt.Printf("str[%d] = %q\n", index, val)/*正常*/
	}
}

使用for循环结构时,将字符串转换为rune切片类型时,可以正确显示字符串信息:

	var str string = "Hello World!数风流人物,还看今朝"
	str2 := []rune(str)
	for i := 0; i < len(str2); i++ {
		fmt.Printf("str[%d] = %c\n", i, str2[i])
	}

1.4 while 和do…while循环结构

在Go语言中,没有while和do…while结构, 但是可以使用for循环结构来实现对应的功能。

  • 使用for实现while:
	for{
		循环条件判断语句

		循环语句执行体
	}
  • 使用for实现do…while:
	for{
		循环语句执行体

		循环条件判断语句
	}

1.5 多种循环结构

  • 打印九九乘法表
func demo1() {
	var a = 9

	for i := 1; i <= a; i++ {
		for j := 1; j <= i; j++ {
			fmt.Printf("%v x %v = %v\t", j, i, i*j)
		}
		fmt.Println("")
	}

}

运行结果如下:

1 x 1 = 1	
1 x 2 = 2	2 x 2 = 4	
1 x 3 = 3	2 x 3 = 6	3 x 3 = 9	
1 x 4 = 4	2 x 4 = 8	3 x 4 = 12	4 x 4 = 16	
1 x 5 = 5	2 x 5 = 10	3 x 5 = 15	4 x 5 = 20	5 x 5 = 25	
1 x 6 = 6	2 x 6 = 12	3 x 6 = 18	4 x 6 = 24	5 x 6 = 30	6 x 6 = 36	
1 x 7 = 7	2 x 7 = 14	3 x 7 = 21	4 x 7 = 28	5 x 7 = 35	6 x 7 = 42	7 x 7 = 49	
1 x 8 = 8	2 x 8 = 16	3 x 8 = 24	4 x 8 = 32	5 x 8 = 40	6 x 8 = 48	7 x 8 = 56	8 x 8 = 64	
1 x 9 = 9	2 x 9 = 18	3 x 9 = 27	4 x 9 = 36	5 x 9 = 45	6 x 9 = 54	7 x 9 = 63	8 x 9 = 72	9 x 9 = 81	

1.6 break

  • 生成随机数的package为:rand。 https://golang.org/pkg/math/rand/

    • rand.Intn(): 生成[0, n)范围的随机数。相同的种子生成相同的伪随机数,种子不同生成的随机数也不同,因此通常使用时间作为随机种子
      官网示例程序如下:
      package main
    
      import (
      	"fmt"
      	"math/rand"
      )
    
      func main() {
      	// Seeding with the same value results in the same random sequence each run.
      	// For different numbers, seed with a different value, such as
      	// time.Now().UnixNano(), which yields a constantly-changing number.
      	rand.Seed(86)
      	fmt.Println(rand.Intn(100))
      	fmt.Println(rand.Intn(100))
      	fmt.Println(rand.Intn(100))
    
      }
    
  • 生成时间的package为:time。 https://golang.org/pkg/time/

    • 通常使用时间作为生成随机数的种子,如time.Unix, time.UnixNano,他们分别返回自1970.1.1年以来的秒数和纳秒数
  • break入门示例:

func main() {
	for {
		rand.Seed(time.Now().UnixNano())
		randNum := rand.Intn(100) + 1

		fmt.Println(randNum)
		if randNum == 99 {
			break
		}
	}
}
  • break注意事项
    • break默认跳出最近的循环结构
    • break可以通过标签来指定循环结构
      func demo2() {
      Lable1:
      	for i := 0; i < 6; i++ {
      	Lable2:
      		for j := 0; j < 10; j++ {
      			fmt.Println(i, j)
      			if j == 6 {
      				break Lable1 /*break默认退出的是最近的循环*/
      			} else if j == 20 {
      				break Lable2
      			}
      		}
      	}
      }
      

1.7 continue

  • 用于结束本次循环,继续执行下一次循环
  • 与break一样,支持通过标签跳转到指定循环中

1.8 goto语句

  • Go语言中支持goto操作,同其他语言一样不推荐使用。goto的基本语法:
	goto lable

	... ...

	lable:
	xxx.xxx

goto入门示例:

func main() {

	fmt.Println("钟山风雨起苍黄")
	fmt.Println("百万雄师过大江")
	goto XXX
	fmt.Println("虎踞龙盘今胜昔")
	fmt.Println("天翻地覆慨而慷")
	fmt.Println("宜将剩勇追穷寇")
	fmt.Println("不可沽名学霸王")

XXX:
	fmt.Println("天若有情天亦老")
	fmt.Println("人间正道是沧桑")
}

执行结果如下:

钟山风雨起苍黄
百万雄师过大江
天若有情天亦老
人间正道是沧桑

1.9 return语句

  • 退出函数
  • 如果在main函数中则是退出程序
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

叨陪鲤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值