douhao2721 2019-08-07 10:20
浏览 44
已采纳

在GO中将字符串解析为具有常见错误消息的不同类型[重复]

This question already has an answer here:

I want parse []string values into particular types (e.g. int, float etc), so I must use different parse functions for different lines. My code:

value, err := strconv.Atoi(line[1])
value1, err := strconv.ParseFloat(line[4], 6)
value2, err := strconv.ParseFloat(line[5], 6)
value3, err := strconv.Atoi(line[2])

I must be sure that every value was parsed so for every value I must have err != nil. Is there any approach to make it with one common error without

if err != nil {
 return 
}

after each line?

</div>
  • 写回答

1条回答 默认 最新

  • dongqian5569 2019-08-07 10:31
    关注

    You can use fmt.Sscanf do do this with one error check:

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        var i int
        var j float64
        var k int
        if _, err := fmt.Sscanf("1,3.14,5", "%d,%f,%d", &i, &j, &k); err != nil {
            panic(err)
        }
        fmt.Println(i, j, k)
    }
    

    You'll need to join the lines with some separator but that's trivial.

    Also, there's a discussion about making handling of multiple errors nicer for Go 2, I'm not sure what the status of it is at the moment, but you can read about it here: https://go.googlesource.com/proposal/+/master/design/go2draft-error-handling-overview.md

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

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题