7 fallthrough关键字【技】
Go里面switch默认相当于每个case最后带有break,匹配成功后不会自动向下执行其他case,而是跳出整个switch, 但是可以使用fallthrough强制执行后面的case代码。
func main() {
i := 10
switch i {
case 1:
fmt.Println(1)
case 5:
fmt.Println(5)
fallthrough
case 10:
fmt.Println(10)
fallthrough
case 20:
fmt.Println(20)
default:
fmt.Println("default")
}
}
运行结果:
10
20
8 简式变量声明仅能在函数内部使用【易】
什么是简式变量声明呢,我们知道Go声明变量有两种方式
// 第一种
var i int
i = 10
// 第二种 (简式变量声明)
i := 10
而第二种变量声明就不可以在方法外使用
9 interface断言【易】
func main() {
var value interface{}
value = "hello"
str := value.(string)
fmt.Println(str)
value = 100
i := value.(int32)
fmt.Println(i)
}
运行结果:
hello
panic: interface conversion: interface {} is int, not int32
......
解决方式:
在断言之前先做一个类型判断
func main() {
var value interface{}
value = 100
switch value.(type) {
case int32:
fmt.Println(value.(int32))
case string:
fmt.Println(value.(string))
case int:
fmt.Println(value.(int))
}
}
当然GitHub有更好的方式可以将interface类型转化成我们需要的类型,比如cast插件。
参考:
https://chai2010.cn/advanced-go-programming-book/appendix/appendix-a-trap.html
https://errorsingo.com/
https://www.kancloud.cn/gopher_go/go/848998
https://blog.csdn.net/Guzarish/article/details/119627758