使用strconv.ParseInt与ints的惯用方式

huangapple go评论110阅读模式
英文:

Idiomatic way to use strconv.ParseInt with ints

问题

我最终写出了这样的代码。我需要一个普通的int(用于其他函数调用),但是parseInt只能产生64位的int:

  1. i64, err := strconv.ParseInt(s, 10, 0)
  2. if err != nil {
  3. fmt.Println("解析失败:", s)
  4. }
  5. 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:

  1. i64, err := strconv.ParseInt(s, 10, 0)
  2. if err != nil {
  3. fmt.Println("parsing failed for", s)
  4. }
  5. 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.ParseIntbitSize参数

  1. package main
  2. import (
  3. "fmt"
  4. "strconv"
  5. )
  6. // 32或64,取决于平台
  7. const IntBits = 1 << (^uint(0)>>32&1 + ^uint(0)>>16&1 + ^uint(0)>>8&1 + 3)
  8. func printInt(i int) {
  9. fmt.Println(i)
  10. }
  11. func main() {
  12. s := "-123123112323231231"
  13. i64, err := strconv.ParseInt(s, 10, IntBits)
  14. if err != nil {
  15. fmt.Println("解析失败:", s)
  16. }
  17. i := int(i64)
  18. printInt(i)
  19. i64, err = strconv.ParseInt(s, 10, 32)
  20. if err != nil {
  21. fmt.Println("解析失败:", s)
  22. }
  23. i = int(i64)
  24. printInt(i)
  25. }

Playground


输出

  1. -123123112323231231
  2. 解析失败: -123123112323231231
  3. -2147483648
英文:

Use the bitSize parameter of strconv.ParseInt

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;strconv&quot;
  5. )
  6. // 32 or 64 depending on platform
  7. const IntBits = 1 &lt;&lt; (^uint(0)&gt;&gt;32&amp;1 + ^uint(0)&gt;&gt;16&amp;1 + ^uint(0)&gt;&gt;8&amp;1 + 3)
  8. func printInt(i int) {
  9. fmt.Println(i)
  10. }
  11. func main() {
  12. s := &quot;-123123112323231231&quot;
  13. i64, err := strconv.ParseInt(s, 10, IntBits)
  14. if err != nil {
  15. fmt.Println(&quot;parsing failed for &quot;, s)
  16. }
  17. i := int(i64)
  18. printInt(i)
  19. i64, err = strconv.ParseInt(s, 10, 32)
  20. if err != nil {
  21. fmt.Println(&quot;parsing failed for &quot;, s)
  22. }
  23. i = int(i64)
  24. printInt(i)
  25. }

Playground


Output

  1. -123123112323231231
  2. parsing failed for -123123112323231231
  3. -2147483648

huangapple
  • 本文由 发表于 2013年7月16日 00:23:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/17659021.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定