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 HC32L176调试了一个通过TIMER5+DMA驱动WS2812B
  • ¥15 三菱FX系列PLC串口指令
  • ¥15 cocos的js代码调用wx.createUseInfoButton问题!
  • ¥15 关于自相关函数法和周期图法实现对随机信号的功率谱估计的matlab程序运行的问题,请各位专家解答!
  • ¥15 Python程序,深度学习,有偿私
  • ¥15 扫描枪扫条形码出现问题
  • ¥35 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型