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

golang语言switch与case

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

golang语言switch与case

package main

import "fmt"

func main() {
	i := 10
	switch i {
	case 1:
		fmt.Println("i is equal to 1")
	case 2, 3, 4:
		fmt.Println("i is equal to 2,3 or 4")
	case 10:
		fmt.Println("i is equal to 10")
	default:
		fmt.Println("all i know is that i is an  integer")
	}
}

有些时候需要写很多的if else来实现一些逻辑处理,switch语法就能解决这个问题

switch  sEXPR {

CASE expr1:

   some   instructions

case expr2:

   some  other instuctions

}

case 取值类型必须一致,go的swith非常灵活,表达式不必是常量或者整数,执行的过程从上至下,知道找到匹配值,如果switch没有表达式,他会匹配true

我们吧很多值聚合在了一个case里面,go里面switch默认相当于每个case最后带有break,匹配成功后不会自动向下执行其他case,而是跳出整个swtich,但是可以使用fallthrough强制执行后面case代码

package main

import "fmt"

func main() {
	integer := 4
	switch integer {
	case 4:
		fmt.Println("the integer was <= 4&
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/902978.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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