3

Golang中Switch的使用

 1 year ago
source link: https://studygolang.com/articles/7673?fr=sidebar
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Golang中Switch的使用

sydbfhwj · 2016-08-11 02:00:12 · 4734 次点击 · 预计阅读时间不到 1 分钟 · 大约8小时之前 开始浏览    
这是一个创建于 2016-08-11 02:00:12 的文章,其中的信息可能已经有所发展或是发生改变。

Go语言中文网提示您:以下内容是错误的!

跟一般语言的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分支走错,逻辑基本就错了。



有疑问加站长微信联系(非本文作者)

280

本文来自:CSDN博客

感谢作者:sydbfhwj

查看原文:Golang中Switch的使用

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK