How do I get a function to return data when go panic?

  • 2020-06-23 00:38:47
  • OfStack

Here's the problem: if a function executes properly, it returns 0, and if panic, it returns 1.


package main 
import "fmt" 
func test() int {
 defer func() {
 if err := recover(); err != nil {
  return 1
 }
 }()
 var p *int
 *p = 0
 return 0
}
func main() {
 fmt.Println("ret is", test())
 for {}
}

This obviously doesn't work, because that return 1 is for anonymous functions, not test functions.

Here's a neat trick:


package main 
import "fmt" 
func test() (a int) {
 defer func() {
 if err := recover(); err != nil {
  a = 1
 }
 }()
 var p *int
 *p = 0
 return 0
}
func main() {
 fmt.Println("ret is", test())
 for {}
}

OK.

Not much said.

conclusion


Related articles: