go switch 基本使用

15 篇文章 0 订阅
1. 常用switch, 一个case 多个条件, 默认情况下 case 最后自带 break 语句,匹配成功后就不会执行其他 case
var lang string

	lang = "js"

	//常用switch, 一个case 多个条件, 默认情况下 case 最后自带 break 语句,匹配成功后就不会执行其他 case
	switch lang {
	case "java":
		println("this case is java")
	case "go", "js":
		println("this case is go")
		println("this case also is js")
	case "php":
		println("this case is php")
	default:
		println("this case is python")
	}

	//输出结果
	//this case is go
	//this case also is js
2. fallthrough 会强制执行后面的 case 语句,fallthrough 不会判断下一条 case 的表达式结果是否为 true。
var lang string

	lang = "js"
	
switch lang {
	case "java":
		println("this case is java")
	case "go", "js":
		println("this case is go")
		println("this case also is js")
		fallthrough
	case "php":
		println("this case is php")
	default:
		println("this case is python")
	}

	//输出结果
	//this case is go
	//this case also is js
	//this case is php
3. 类型判断
var x interface{}

	switch i:= x.(type) {
	case int:
		fmt.Printf("x type is %T", i)
	case string:
		fmt.Printf("x type is %T", i)
	case bool, nil:
		fmt.Printf("x type is %T", i)
	}

	//输出结果
	//x type is <nil>

代码地址:https://github.com/hufeng903/go-demo/tree/master/switch

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值