我已经看过每个例子(例如getting panic() argument in defer function in GO lang),我希望这可行,但它不是。强制发生错误时,err
返回字符串保持空白,但打印错误的字符串会显示预期的错误。
我确定我错过了一些明显的东西,却无法找到它。一点帮助?
// expected error example:
// chk, err := equal("a", map[string]string{"a"})
//
func Equal(a interface{}, b interface{}) (check bool, err string) {
defer func() {
if catch := recover(); catch != nil {
check = false
// this prints
fmt.Printf("%v\n", catch)
err = fmt.Sprint(catch)
}
}()
return a == b, ""
}
顺便说一句:
go version go1.2.1 linux/amd64
答案 0 :(得分:2)
正如@nos指出的那样,这里没有恐慌。
此示例按预期工作:
package main
import "fmt"
func equal(a interface{}, b interface{}) (check bool, err string) {
defer func() {
if catch := recover(); catch != nil {
check = false
fmt.Printf("recover: %v\n", catch)
err = fmt.Sprint(catch)
} else {
fmt.Printf("recover: none\n")
}
}()
return a == b, ""
}
func main() {
chk, err := equal("a", "a")
fmt.Printf("a == a\n")
fmt.Printf("chk: %v\n", chk)
fmt.Printf("err: %v\n", err)
fmt.Println()
chk, err = equal("a", 1)
fmt.Printf("a == 1\n")
fmt.Printf("chk: %v\n", chk)
fmt.Printf("err: %v\n", err)
fmt.Println()
chk, err = equal([]int{1}, []int{1})
fmt.Printf("[]int{1}, []int{1}\n")
fmt.Printf("chk: %v\n", chk)
fmt.Printf("err: %v\n", err)
}
// Output:
//
// recover: none
// a == a
// chk: true
// err:
// recover: none
//
// a == 1
// chk: false
// err:
// recover: runtime error: comparing uncomparable type []int
//
// []int{1}, []int{1}
// chk: false
// err: runtime error: comparing uncomparable type []int