dre93205 2016-09-23 18:46
浏览 52
已采纳

我无法从strconv软件包访问err.Err

I am probably missing something really simple here:

package main

import (
    "fmt"
    "strconv"
    "reflect"
)

func main() {
    s := "abd"
    fmt.Println(s)
    _, err := strconv.Atoi(s)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(reflect.TypeOf(err))

    fmt.Println(err.Err)

}

I am trying to extract the error itself e.g. ErrSyntax or ErrRange, but I am not able to do so.

After looking at:

https://golang.org/src/strconv/atoi.go?s=3604:3671#L16

I see that err is a pointer to strconv.NumError

    15  // A NumError records a failed conversion.
    16  type NumError struct {
    17      Func string // the failing function (ParseBool, ParseInt, ParseUint, ParseFloat)
    18      Num  string // the input
    19      Err  error  // the reason the conversion failed (ErrRange, ErrSyntax)
    20  }

And Err is the field that holds either ErrRange of ErrSyntax. Therefore, I thought that err.Err would work, but I get:

err.Err undefined (type error has no field or method Err

Err is public, am I missing something with visibility rules?

What am I missing?

  • 写回答

1条回答 默认 最新

  • dqm4675 2016-09-23 18:56
    关注

    Use a type assertion to get the *strconv.NumError value:

    if e, ok := err.(*strconv.NumError); ok {
        fmt.Println("e.Err", e.Err)
    }
    

    playground example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改