Golang之控制语句
source link: https://studygolang.com/articles/27843
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
package main //if 条件判断 import "fmt" func main (){ age := 19 if age > 18{ fmt.Printf("澳门线上赌场开业啦") }else if age<18 && age>0{ fmt.Printf("快去上网课吧!!") }else{ fmt.Printf("error!") } } 复制代码
for
循环
在Go语言中,只有for循环,没有C语言中的while循环。
-
break
和continue
可以改变控制流,break
表示从当前循环跳出,结束循环。continue
表示跳过此次循环,进行下一次循环。
for循环包括两种:
1.类似C语言中的循环
需要注意的是,必须将{与for循环的末尾放在同一行。否则会发生编译错误。
- for循环普通用法
package main import "fmt" func main(){ //三个语句都可以省略,但需要保留“;” for i:=0;i<10;i++{ for j:=0;j<5;j++{ fmt.Println(i) } } 复制代码
-
for
可以类似于C语言中的while
使用,方法如下:
func for_while(){ i := 0 for i<10{ i++ fmt.Println(i) } } 复制代码
2. for runge
循环
在数据类型的区间(range)上边遍历,比如字符串,或者切片。
通过 for range
遍历的返回值有以下规律:
- 数组、切片、字符串返回索引(数组下标)和值。
- map返回键和值。
- 通道(channel)只返回通道内的值。
package main import "fmt" func main(){ // for runge循环 str := "cyz is good" for _ ,v := range str{ fmt.Println(v) } 复制代码
switch
多路选择
Go语言并不需要显式地在每一个 case
后写 break
,语言默认执行完 case
后的逻辑语句会自动退出。 如果想让之后的语句都执行同一个逻辑。可以自己加 fallthrough
switch语句分两种类型
a.有对象
package main import "fmt" func main (){ var n = 5 switch n { case 1:fmt.Println("111") case 2:fmt.Println("222") case 3:fmt.Println("333") case 4:fmt.Println("444") case 5:fmt.Println("555") } } 复制代码
b.无对象
无对象等价于 switch true
,然后将每个 case
表达式之后的值跟 true
值相比较,例子如下:
package main import "fmt" func main (){ var n = 5 switch { case n == 1:fmt.Println("111") case n == 2:fmt.Println("222") case n == 3:fmt.Println("333") case n == 4:fmt.Println("444") case n == 5:fmt.Println("555") } } 复制代码
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK