必须
用panic、recover和defer进行通用的错误处理。
目前,它必须与gotip一起使用。
$ go install golang.org/dl/gotip@latest
$ gotip download
使用方法。
// main.go
package main
import (
"fmt"
"os"
"github.com/mcesar/must"
)
func main() {
fmt.Println(f())
}
func f() (err error) {
defer must.Handle(&err)
f := must.Do(os.Open("file"))
defer f.Close()
// ...
return nil
}
要运行。
$ gotip run main.go
基准测试。
$ gotip test -bench=.
goos: darwin
goarch: arm64
pkg: github.com/mcesar/must
BenchmarkMustErrorHandlingWithoutDelay-8 9594230 114.1 ns/op
BenchmarkRegularErrorHandlingWithoutDelay-8 73931268 15.71 ns/op
BenchmarkMustErrorHandlingWith10msDelay-8 100 11777532 ns/op
BenchmarkRegularErrorHandlingWith10msDelay-8 100 11590843 ns/op
文档
func Do
func Do[A any](a A, err error) A
如果err !=nil,Do将返回a或恐慌。
func Do0
func Do0(err error)
如果err !=nil,则Do panics。
func Do2
func Do2[A, B any](a A, b B, err error)
Do2 返回 a 和 b 或恐慌,如果 err !=nil。
函数 Handle
func Handle(err *error)
如果是错误,Handle 将 err 设置为恢复的值。
func Handlef
func Handlef(err *error, str string)
Handlef将err设置为恢复的值,如果它是一个错误,
根据指定的格式化字符串进行包装
。