AFAIK,无法自动获取执行最后一次返回的行。
然而,有了一个小帮手,一个人可以拥有:
package main
import (
"fmt"
"runtime"
)
func here(s string, args ...interface{}) error {
_, fname, fline, _ := runtime.Caller(1)
h := fmt.Sprintf("%s:%d: ", fname, fline)
return fmt.Errorf(h+s, args...)
}
func foo(i int) error {
if i == 2 {
return here("cannot handle %d", i) // line 16
}
if i%3 == 0 {
return here("also cannot handle %d", i) // line 20
}
return nil
}
func main() {
fmt.Println(foo(2))
fmt.Println(foo(3))
fmt.Println(foo(4))
}
操场
输出:
/tmpfs/gosandbox-92c2a0f2_32bdf9d9_3c7d2a0a_80ba8510_f68d9721/prog.go:16: cannot handle 2
/tmpfs/gosandbox-92c2a0f2_32bdf9d9_3c7d2a0a_80ba8510_f68d9721/prog.go:20: also cannot handle 3
<nil>