英文:
Golang converting string to int64
问题
我想将一个字符串转换为int64类型。我在strconv
包中找到了Atoi
函数。它似乎将一个字符串转换为int类型并返回:
// Atoi是ParseInt(s, 10, 0)的简写。
func Atoi(s string) (i int, err error) {
i64, err := ParseInt(s, 10, 0)
return int(i64), err
}
实际上,ParseInt函数返回的是int64类型:
func ParseInt(s string, base int, bitSize int) (i int64, err error){
//...
}
所以,如果我想从字符串中获取int64类型,应该避免使用Atoi,而是使用ParseInt函数。或者是否有一个名为Atio64的隐藏函数?
英文:
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?
答案1
得分: 242
将字符串解析为int64的示例:
// 使用有符号64位整数的最大值。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))
输出:
Hello, 9223372036854775807 with type int64!
链接:https://play.golang.org/p/XOKkE6WWer
英文:
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!
答案2
得分: 107
不,没有Atoi64。你还应该将64作为最后一个参数传递给ParseInt,否则在32位系统上可能无法产生预期的值。
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
英文:
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.
var s string = "9223372036854775807"
i, _ := strconv.ParseInt(s, 10, 64)
fmt.Printf("val: %v ; type: %[1]T\n", i)
答案3
得分: 5
另一个选项:
package main
import "fmt"
func main() {
var n int64
fmt.Sscan("100", &n)
fmt.Println(n == 100)
}
https://golang.org/pkg/fmt#Sscan
英文:
Another option:
package main
import "fmt"
func main() {
var n int64
fmt.Sscan("100", &n)
fmt.Println(n == 100)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论