2

我最终编写了这样的代码。我需要一个常规的 int (用于其他一些函数调用),但 parseInt 只产生 64 位整数:

i64, err := strconv.ParseInt(s, 10, 0)
if err != nil {
    fmt.Println("parsing failed for", s)
}
i := int(i64)

http://play.golang.org/p/_efRm7yp3o

有没有办法避免额外的演员?还是一种使这更惯用的方法?

4

2 回答 2

3

您可以使用strconv.Atoiwhich wrapsstrconv.ParseInt以您想要的方式。

于 2013-07-15T16:32:13.680 回答
0

使用strconv.ParseIntbitSize parameter _

package main

import (
        "fmt"
        "strconv"
)

// 32 or 64 depending on platform
const IntBits = 1 << (^uint(0)>>32&1 + ^uint(0)>>16&1 + ^uint(0)>>8&1 + 3)

func printInt(i int) {
        fmt.Println(i)
}

func main() {
        s := "-123123112323231231"
        i64, err := strconv.ParseInt(s, 10, IntBits)
        if err != nil {
                fmt.Println("parsing failed for ", s)
        }
        i := int(i64)
        printInt(i)

        i64, err = strconv.ParseInt(s, 10, 32)
        if err != nil {
                fmt.Println("parsing failed for ", s)
        }
        i = int(i64)
        printInt(i)
}

操场


输出

-123123112323231231
parsing failed for  -123123112323231231
-2147483648
于 2013-07-15T16:32:45.620 回答