英文:
Idiomatic way to use strconv.ParseInt with ints
问题
我最终写出了这样的代码。我需要一个普通的int(用于其他函数调用),但是parseInt只能产生64位的int:
i64, err := strconv.ParseInt(s, 10, 0)
if err != nil {
fmt.Println("解析失败:", s)
}
i := int(i64)
http://play.golang.org/p/_efRm7yp3o
有没有办法避免额外的类型转换?或者有没有办法使这个代码更符合惯用写法?
英文:
I end up writing code like this. I need a regular int (for some other function call), but parseInt only produces 64 bit ints:
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
Is there a way to avoid the extra cast? Or a way to make this more idiomatic?
答案1
得分: 3
你可以使用strconv.Atoi
,它以你想要的方式包装了strconv.ParseInt
。
英文:
You can use strconv.Atoi
which wraps strconv.ParseInt
in a way you want.
答案2
得分: 0
使用strconv.ParseInt
的bitSize参数
。
package main
import (
"fmt"
"strconv"
)
// 32或64,取决于平台
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("解析失败:", s)
}
i := int(i64)
printInt(i)
i64, err = strconv.ParseInt(s, 10, 32)
if err != nil {
fmt.Println("解析失败:", s)
}
i = int(i64)
printInt(i)
}
输出
-123123112323231231
解析失败: -123123112323231231
-2147483648
英文:
Use the bitSize parameter
of strconv.ParseInt
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)
}
Output
-123123112323231231
parsing failed for -123123112323231231
-2147483648
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论