在Go语言中,`errors.Is`函数结合`TypeOf`和`Comparable`用于判断错误类型。

huangapple go评论72阅读模式
英文:

TypeOf with Comparable in errors.Is

问题

errors.Is(err, target error) 函数用于检查 target 是否可比较。

在给定的代码中,首先检查 target 是否为 nil,如果是,则返回 err == target 的比较结果。

接下来,通过使用 reflectlite.TypeOf(target).Comparable() 判断 target 是否可比较。如果 target 是可比较的,并且 err 等于 target,则返回 true

对于所有的接口类型,在 Go 中都是可比较的,包括 error 接口。因此,这个函数可以处理任何情况。

英文:

I am learning how error comparison works in Go and found something I cannot understand.

Function errors.Is(err, target error) checks if target is Comparable.

func Is(err, target error) bool {
	if target == nil {
		return err == target
	}

	isComparable := reflectlite.TypeOf(target).Comparable()
	for {
		if isComparable && err == target {
			return true
		}

Source

Which case does this call handle given that all interfaces in Go are comparable and error is an interface?

答案1

得分: 3

接口值是可比较的,但比较过程可能在运行时引发 panic。根据规范的说明:

如果两个具有相同动态类型的接口值进行比较,且该类型的值不可比较,则会在运行时引发 panic。

这个检查可以避免在目标的具体类型不可比较时引发 panic。

以下是一个示例:

type E []byte
func (e E) Error() string { return string(e) }
func (e E) Is(target error) bool {
    t, ok := target.(E)
    return ok && bytes.Equal(e, t)
}

var a error = E{}
var b error = E{}
fmt.Println(errors.Is(a, b)) // 输出 true
fmt.Println(a == b)          // 因为切片不可比较,所以引发 panic
英文:

Interfaces values are comparable, but the comparison can panic at run-time. The specification says:

> A comparison of two interface values with identical dynamic types causes a run-time panic if values of that type are not comparable.

The check prevents a panic by skipping the comparison when the target's concrete type is not comparable.

Here's an example:

type E []byte
func (e E) Error() string { return string(e) }
func (e E) Is(target error) bool {
	t, ok := target.(E)
	return ok && bytes.Equal(e, t)
}

var a error = E{}
var b error = E{}
fmt.Println(errors.Is(a, b)) // prints true
fmt.Println(a == b)          // panics because slices are not comparable

huangapple
  • 本文由 发表于 2022年1月17日 00:30:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/70731980.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定