Pregunta

I want to convert a string to an int64. What I find from the strconv package is the Atoi function. It seems to cast a string to an int and return it:

// Atoi is shorthand for ParseInt(s, 10, 0).
func Atoi(s string) (i int, err error) {
        i64, err := ParseInt(s, 10, 0)
    return int(i64), err
}

The ParseInt actually returns an int64:

func ParseInt(s string, base int, bitSize int) (i int64, err error){
     //...
}

So if I want to get an int64 from a string, should I avoid using Atoi, instead use ParseInt? Or is there an Atio64 hidden somewhere?

¿Fue útil?

Solución 2

No, there's no Atoi64. You should also pass in the 64 as the last parameter to ParseInt, or it might not produce the expected value on a 32-bit system.

Adding abbreviated example:

var s string = "9223372036854775807"
i, _ := strconv.ParseInt(s, 10, 64)
fmt.Printf("val: %v ; type: %[1]T\n", i)

https://play.golang.org/p/FUC8QO0-lYn

Otros consejos

Parsing string into int64 example:

// Use the max value for signed 64 integer. http://golang.org/pkg/builtin/#int64
var s string = "9223372036854775807"
i, err := strconv.ParseInt(s, 10, 64)
if err != nil {
    panic(err)
}
fmt.Printf("Hello, %v with type %s!\n", i, reflect.TypeOf(i))

output:

Hello, 9223372036854775807 with type int64!

https://play.golang.org/p/XOKkE6WWer

Another option:

package main
import "fmt"

func main() {
   var n int64
   fmt.Sscan("100", &n)
   fmt.Println(n == 100)
}

https://golang.org/pkg/fmt#Sscan

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top