面试题
这是Go Quiz系列的第3篇,关于Go语言的分号规则和switch
的特性。
这道题比较tricky,通过这道题可以加深我们对Go语言里的分号:
规则和switch
特性的理解。
package main func f() bool { return false } func main() { switch f() { case true: println(1) case false: println(0) default: println(-1) } }
- A: 1
- B: 0
- C: -1
这道题主要考察以下知识点:
- Go语言里的分号
:
规则 switch
后面的{
换行后编译器会在背后做什么?
解析
Go语言和C++
一样,在每行语句(statement)的末尾是以分号:
结尾的。
看到这里,你可能会有点懵,是不是在想:我写Go代码的时候也没有在语句末尾加分号啊。。。
那是因为Go编译器的词法解析程序自动帮你做了这个事情,在需要加分号的地方给你加上了分号。
如果你在代码里显示地加上分号,编译器是不会报错的,只是Go不需要也不建议显示加分号,一切交给编译器去自动完成。
那编译器是怎么往我们代码里插入分号:
的呢?规则是什么?我们看看官方文档的说法:
When the input is broken into tokens, a semicolon is automatically inserted into the token stream immediately after a line's final token if that token is
- an identifier
- an integer, floating-point,