Golang中Switch的使用

时间:2022-07-08 05:29:43

跟一般语言的Switch有点不一样,Golang在使用两个case的时候,是第一个是不生效的。

如下的代码

switch (type) {
	case 1:
	case 2:
		return "a";
	case 3:
		return "b"
	default:
		return "c"
}


在Java中,输入1,2都是返回a,输入3是返回b,其他是c。

但是在Go中,输入1竟然是返回c,被坑过几次。

如果想在Go中达到类似Java的效果,只能这么写:

switch type {
	case 1:
		return "a"
	case 2:
		return "a";
	case 3:
		return "b"
	default:
		return "c"
}

一条条写明显太费劲了,所以还可以这么写:

switch type {
	case 1, 2:
		return "a";
	case 3:
		return "b"
	default:
		return "c"
}
小细节却不能不注意,因为如果switch分支走错,逻辑基本就错了。

相关文章