douyingp82418 2017-03-22 07:43
浏览 39

转到AST /类型-如何判断错误?

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}"
}
  • 写回答

2条回答 默认 最新

  • douzhong1730 2017-03-22 08:56
    关注

    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
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向