栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

go if-else && switch

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

go if-else && switch

if-else 判断与选择

判断是否为真,为真则执行代码块的输出,为false则不执行。

if true {
    fmt.Println("true")
}

选择

func main() {
	var str string = "a"
	// 要么走第一个代码块,要么走第二个代码块
	if str=="a" {
		fmt.Println("str = ",str)
	}else {
		fmt.Println("str != ",str)
	}
}
// 多种选择,只会选择一个分支进入并执行对应的代码块,没有找到对应就会进入默认代码块
func main()  {
	var str int = 0
	if str > 0 && str <= 5 {
		fmt.Println("str 进入 ~5 范围")
	}else if str > 5 && str <=10 {
		fmt.Println("str 进入 5 ~10 范围")
	}else if str > 10 && str <=100 {
		fmt.Println("str 进入 10 ~100 范围")
	}else if str > 100 {
		fmt.Println("str 进入 100~  范围")
	}else { // 默认代码块
		fmt.Println("默认")
	}
}
switch 选择

条件语句,将表达式的值与可能匹配的选项列表进行比较,并执行相应的代码块,执行后结束switch。

func main() {
    // switch 示例: switch表达式的与case的表达式的值(多个case的值均为唯一的)进行比较,相同则进入对应代码块,没有相匹配的则进入default默认代码块(可省略不写); 
	i := 3
	switch i {
	case 1:
		fmt.Println(i," ->  1") 
	case 2:
		fmt.Println(i," ->  2")
	case 3:
        fmt.Println(i," ->  3") //输出: 3 -> 3
	case 4:
		fmt.Println(i," ->  4")
	case 5:
		fmt.Println(i," ->  5")
	default:
		fmt.Println(i," ->  default")
	}
}

func main() {
	// switch 示例
	switch i := 3; i { //在switch表达式之前声明初始化i,但i的作用域只限制于switch中
	case i: //如果两个的都是i即两个case的值相同i是变量,3是常量,顺序执行第1个。
		fmt.Println(i," ->  1")//输出: 3 -> 1
	case 2:
		fmt.Println(i," ->  2")
	case 3:
		fmt.Println(i," ->  3")
	case 4:
		fmt.Println(i," ->  4")
	default:
		fmt.Println(i," ->  default")
	}
   // fmt.Println(i)
}

func main() {
	// switch 示例
	i := 3
	switch  { // switch 表达式可以省略, 默认为true
	case i <= 5:
		fmt.Println(i," ->  1")//输出: 3 -> 5
	case i <= 10:
		fmt.Println(i," ->  2")
	case i <= 100:
		fmt.Println(i," ->  3")
	default:
		fmt.Println(i," ->  default")
	}
}
Fallthrough
func main() {
	// switch 示例
	switch i := getNumber();{// 初始化并赋值i
	case i <= 5:
		fmt.Println(i," ->  1")
	case i <= 10:
		fmt.Println(i," ->  2")
        fallthrough // fallthrough 强制(case的表达式是多少都会执行)执行下一个case代码块,只能放置case末尾
	case i <= 100:  // 	case false: 也会执行输出:10  ->  3
		fmt.Println(i," ->  3")
	case i <= 1000:
		fmt.Println(i," ->  4")
	default:
		fmt.Println(i," ->  default")
	}
}
func getNumber() int {
	return 10
}
// 输出:
// 10  ->  2
// 10  ->  3
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/709181.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号