dqmq0654 2012-10-04 23:18
浏览 54
已采纳

从字符串转换为整数(如果失败,则抛出错误)

My apologies if this is a beginner question, but I simply can't seem to find any solution for this. I'm trying to take an argument that can be either a string or an int, depending on the context, and I need to determine which type, (then convert it to int if it is indeed that type.)

Thank you :)

  • 写回答

3条回答 默认 最新

  • duanliang789262 2012-10-04 23:36
    关注

    http://golang.org/pkg/strconv/#Atoi

    func Atoi
    
    func Atoi(s string) (i int, err error)
    Atoi is shorthand for ParseInt(s, 10, 0).
    

    This is an update. To clarify, since Atoi accepts string, then trying to pass an int will cause a compile time error. If you need a check during runtime, then you can do something like this.

    package main
    
    import (
        "fmt"
        "strconv"
        "errors"
    )
    
    func toInt(data interface{}) (n int, err error) {
        switch t := data.(type) {
        case int:
            return t, nil
        case string:
            return strconv.Atoi(t)
        default:
            return 0, errors.New(fmt.Sprintf("Invalid type received: %T", t))
        }
    
        panic("unreachable!")
    }
    
    func main() {
        var (
            n int
            err error
        )
    
        n, _ = toInt("1")
        fmt.Println(n)
    
        n, _ = toInt(2)
        fmt.Println(n)
    
        n, err = toInt(32.3)
        fmt.Println(err)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么