2

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?

Eve Freeman
  • 32,467
  • 4
  • 86
  • 101

2 Answers2

3

You can use strconv.Atoi which wraps strconv.ParseInt in a way you want.

Volker
  • 40,468
  • 7
  • 81
  • 87
0

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

Playground


Output

-123123112323231231
parsing failed for  -123123112323231231
-2147483648
zzzz
  • 87,403
  • 16
  • 175
  • 139
  • this is close to what I'm already doing, I think... I was just trying to avoid the extra boilerplate of `i64, err := ...` immediately followed by `i := int(i64)` – Eve Freeman Jul 15 '13 at 17:25