Go AST / Types – 如何判断错误?

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

Go AST / Types - how to tell an error?

问题

有没有更好的方法来做这个?我需要知道变量v的类型是否是内置的"error"类型。我觉得应该有更简洁的方法来实现这个:

import (
	"go/ast"
	"go/types"
)

func IsError(v ast.Expr, info types.Info) bool {
	t := info.Types[v]
	return t.Type.String() == "error" &&
		t.Type.Underlying().String() == "interface{Error() string}"
}
英文:

Is there a better way of doing this? I need to know if the type of v is the built-in "error" type. I feel like there should be a neater way of doing this:

import (
	"go/ast"
	"go/types"
)

func IsError(v ast.Expr, info types.Info) bool {
	t := info.Types[v]
	return t.Type.String() == "error" &&
		t.Type.Underlying().String() == "interface{Error() string}"
}

答案1

得分: 1

类型断言是检查变量类型的惯用方式。

假设你正在处理一个AST表达式,我会尝试检查底层类型是否为接口,并且是否实现了Error()方法:

isError := func(v ast.Expr, info *types.Info) bool {
    if intf, ok := info.TypeOf(v).Underlying().(*types.Interface); ok {
        return intf.NumMethods() == 1 && intf.Method(0).FullName() == "(error).Error"
    }
    return false
}
英文:

Type assertion is the idiomatic way of checking the type of a variable.

Given you're handling an AST expression, I'd try to check if the underlying type is an interface and if the Error() method is implemented:

isError := func(v ast.Expr, info *types.Info) bool {
	if intf, ok := info.TypeOf(v).Underlying().(*types.Interface); ok {
		return intf.NumMethods() == 1 && intf.Method(0).FullName() == "(error).Error"
	}
	return false
}

答案2

得分: 0

我认为我更喜欢这个解决方案:

https://play.golang.org/p/MA7F4Zpwqt

isError := func(v ast.Expr, info *types.Info) bool {
    if n, ok := info.TypeOf(v).(*types.Named); ok {
        o := n.Obj()
        return o != nil && o.Pkg() == nil && o.Name() == "error"
    }
    return false
}
英文:

I think I prefer this solution:

https://play.golang.org/p/MA7F4Zpwqt

isError := func(v ast.Expr, info *types.Info) bool {
	if n, ok := info.TypeOf(v).(*types.Named); ok {
		o := n.Obj()
		return o != nil && o.Pkg() == nil && o.Name() == "error"
	}
	return false
}

huangapple
  • 本文由 发表于 2017年3月22日 15:43:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/42945530.html
匿名

发表评论

匿名网友

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

确定