golang语言switch与case

golang语言switch与case,第1张

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&

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/989882.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存