go的switch
点击查看代码
package main
import(
"fmt"
)
func testIf(){
var num int =2
if num == 1{
fmt.Printf("num:%d num==1 \n",num)
}else if num == 2{
fmt.Printf("num:%d num==2 \n",num)
}else if num == 3{
fmt.Printf("num:%d num==3 \n",num)
}else if num == 4{
fmt.Printf("num:%d num== 4 \n",num)
}else{
fmt.Printf("num:%d num== 5 \n",num)
}
// fmt.Printf("num3:%d \n",num) // num 是在函数内定义的,在在整个函数的生命周期内都有效
}
func testSwitch(){
var num int =2
switch num {
case 1 :
fmt.Printf("num:%d num==1 \n",num)
case 2 :
fmt.Printf("num:%d num==2 \n",num)
case 3 :
fmt.Printf("num:%d num==3 \n",num)
case 4 :
fmt.Printf("num:%d num==4 \n",num)
case 5 :
fmt.Printf("num:%d num==5 \n",num)
}
}
func testSwitchV2(){
switch num :=6; num {
case 1 :
fmt.Printf("V2num:%d num==1 \n",num)
case 2 :
fmt.Printf("V2num:%d num==2 \n",num)
case 3 :
fmt.Printf("V2num:%d num==3 \n",num)
case 4 :
fmt.Printf("V2num:%d num==4 \n",num)
case 5 :
fmt.Printf("V2num:%d num==5 \n",num)
default:
fmt.Printf("invalid num=%d\n",num)
}
// fmt.Printf("V2num:%d num==5 \n",num) // undefined: num num只在switch语句块中有效,语句块结束,num就没了
}
func testSwitchV3(){
switch num :=2; num {
case 1,2,3,4,5 :
fmt.Printf("V3 num:%d num>=2 and num <=5 \n",num)
case 6,7,8,9,10 :
fmt.Printf("V3 num:%d num>=6 and num <=10 \n",num)
default:
fmt.Printf("num>10 num=%d\n",num)
}
// fmt.Printf("V2num:%d num==5 \n",num) // undefined: num num只在switch语句块中有效,语句块结束,num就没了
}
func testSwitchV4(){
switch num :=666; {
case num>=0 && num <=25 :
fmt.Printf("V3 num:%d num>=0 and num <=25 \n",num)
case num>25 && num <=50 :
fmt.Printf("V3 num:%d num>25 and num <=50 \n",num)
case num>50 && num <=75 :
fmt.Printf("V3 num:%d num>50 and num <=75 \n",num)
case num>75 && num <=100 :
fmt.Printf("V3 num:%d num>75 and num <=100 \n",num)
default:
fmt.Printf("invalid num=%d\n",num)
}
// fmt.Printf("V2num:%d num==5 \n",num) // undefined: num num只在switch语句块中有效,语句块结束,num就没了
}
func testSwitchV5(){
var num =30
switch {
case num>=0 && num <=25 :
fmt.Printf("V3 num:%d num>=0 and num <=25 \n",num)
case num>25 && num <=50 :
fmt.Printf("V3 num:%d num>25 and num <=50 \n",num)
fallthrough
case num>50 && num <=75 :
fmt.Printf("V3 num:%d num>50 and num <=75 \n",num)
fallthrough
case num>75 && num <=100 :
fmt.Printf("V3 num:%d num>75 and num <=100 \n",num)
default:
fmt.Printf("invalid num=%d\n",num)
}
// fmt.Printf("V2num:%d num==5 \n",num) // undefined: num num只在switch语句块中有效,语句块结束,num就没了
}
func testMulti(){
for i:=1;i<10;i++{
for j :=1;j<=i;j++{
fmt.Printf("%d * %d = %d\t",j,i,j*i)
}
fmt.Println()
}
}
func main(){
testIf()
testSwitch()
//testSwitchV2()
//testSwitchV3()
//testSwitchV4()
//testSwitchV5()
//testMulti()
}
写入自己的博客中才能记得长久
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!