string Golang 将字符串转换为 int64
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21532113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Golang converting string to int64
提问by Qian Chen
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:
我想将字符串转换为 int64。我从strconv
包中找到的是Atoi
函数。它似乎将一个字符串转换为一个 int 并返回它:
// 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:
ParseInt 实际上返回一个 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?
因此,如果我想从字符串中获取 int64,是否应该避免使用 Atoi,而是使用 ParseInt?或者是否有隐藏在某处的 Atio64?
采纳答案by Eve Freeman
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.
不,没有 Atoi64。您还应该将 64 作为最后一个参数传递给 ParseInt,否则它可能不会在 32 位系统上产生预期值。
回答by ET-CS
Parsing string into int64 example:
将字符串解析为 int64 示例:
// 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!
您好,9223372036854775807,类型为 int64!