5

Right now I am doing the following in order to parse an integer from a string and then convert it to int type:

tmpValue, _ := strconv.ParseInt(str, 10, 64) //returns int64
finalValue = int(tmpValue)

It is quite verbose, and definitely not pretty, since I haven't found a way to do the conversion in the ParseInt call. Is there a nicer way to do that?

Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
Sergi Mansilla
  • 12,495
  • 10
  • 39
  • 48

3 Answers3

5

It seems that the function strconv.Atoi does what you want, except that it works regardless of the bit size of int (your code seems to assume it's 64 bits wide).

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
3

If you have to write that once in your program than I see no problem. If you need at several places you can write a simple specialization wrapper, for example:

func parseInt(s string) (int, error) {
        i, err := strconv.ParseInt(str, 10, 32)  // or 64 on 64bit tip
        return int(i), err
}

The standard library doesn't aim to supply (bloated) APIs for every possible numeric type and/or their combinations.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
zzzz
  • 87,403
  • 16
  • 175
  • 139
  • I took the liberty of removing the `base` argument, which wasn't being used. Otherwise, +1. – Fred Foo Dec 16 '12 at 13:48
  • Actually, the point about "bloated APIs" is a bit off, since this particular case *is* covered by `strconv.Atoi`. – Fred Foo Dec 16 '12 at 13:53
  • true. You could also call that a lack of generics in Go, but I understand from Pike's blog and other places that I'm not supposed to complain about that ;) – Fred Foo Dec 16 '12 at 14:03
2

Don't forget to check for errors. For example,

package main

import (
    "fmt"
    "strconv"
)

func main() {
    s := "123"
    i, err := strconv.Atoi(s)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(i)
}

Output:

123
peterSO
  • 158,998
  • 31
  • 281
  • 276