ch5/ch5-10 #148
Replies: 6 comments
-
练习5.19 - 断言可以不用先理解透,我就只是简单了解了下=_=||func main() {
ret := practice()
fmt.Println(ret)
}
func practice() (result int) {
defer func() {
if r := recover(); r != nil {
log.Println("Recovered in f", r)
// 断言, 参考第七章7.10节的内容
// see: https://zhuanlan.zhihu.com/p/149015320
// 具体作用为检查接口中是否包含int类型的值, 并返回该值
// panic接受一个类型为any的参数
// 该参数的any类型实际为一个空接口
// 参考Go安装目录 /src/builtin/builtin.go:95 :252
result = r.(int) // 断言 int
}
}()
panic(34)
} |
Beta Was this translation helpful? Give feedback.
-
//5.19
func test() (res int) {
defer func() {
if p := recover(); p != nil {
res = 1
}
}()
panic("?")
} |
Beta Was this translation helpful? Give feedback.
-
func test5() (n int) {
defer func() {
recover()
n = -1
}()
panic(123)
} |
Beta Was this translation helpful? Give feedback.
-
//练习5.19: 使用panic和recover编写一个不包含return语句但能返回一个非零值的函数。
|
Beta Was this translation helpful? Give feedback.
-
package main import "fmt" func main(){ func divide(a, b int) (c int) { |
Beta Was this translation helpful? Give feedback.
-
利用defer覆盖返回值 func f() (a int) {
defer func() {
if r := recover(); r != nil {
a = 1
}
}()
panic("panic")
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
ch5/ch5-10
中文版
https://golang-china.github.io/gopl-zh/ch5/ch5-10.html
Beta Was this translation helpful? Give feedback.
All reactions