猿问

将 strconv.ParseInt 与整数一起使用的惯用方式

我最终编写了这样的代码。我需要一个常规的 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


有没有办法避免额外的演员?或者有什么方法可以让这更地道?


蝴蝶不菲
浏览 247回答 2
2回答

POPMUISE

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

摇曳的蔷薇

使用bitSize parameter的strconv.ParseIntpackage mainimport (&nbsp; &nbsp; &nbsp; &nbsp; "fmt"&nbsp; &nbsp; &nbsp; &nbsp; "strconv")// 32 or 64 depending on platformconst IntBits = 1 << (^uint(0)>>32&1 + ^uint(0)>>16&1 + ^uint(0)>>8&1 + 3)func printInt(i int) {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(i)}func main() {&nbsp; &nbsp; &nbsp; &nbsp; s := "-123123112323231231"&nbsp; &nbsp; &nbsp; &nbsp; i64, err := strconv.ParseInt(s, 10, IntBits)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("parsing failed for ", s)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; i := int(i64)&nbsp; &nbsp; &nbsp; &nbsp; printInt(i)&nbsp; &nbsp; &nbsp; &nbsp; i64, err = strconv.ParseInt(s, 10, 32)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("parsing failed for ", s)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; i = int(i64)&nbsp; &nbsp; &nbsp; &nbsp; printInt(i)}输出-123123112323231231parsing failed for&nbsp; -123123112323231231-2147483648
随时随地看视频慕课网APP

相关分类

Go
我要回答