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

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

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条)

报告相同问题?