英文:
golang Converting math.MinInt64 string to int fails
问题
给定以下函数:
func convertValue(contents string) (int, error) {
return strconv.Atoi(contents)
}
当我运行以下测试时:
var convertValues = []struct {
contents string
value int
}{
{"9223372036854775807", math.MaxInt64},
{"−9223372036854775808", math.MinInt64},
}
func TestConvertValue(t *testing.T) {
for _, values := range convertValues {
value, err := convertValue(values.contents)
if err != nil {
t.Error("Expecting", values.value, "but got error", err.Error())
}
if value != values.value {
t.Error("Expecting", values.value, ", but got", value)
}
}
}
它对于MaxInt64
有效,但对于MinInt64
无效。我在MacBookPro上运行,所以它是在64位上运行的。我已经使用以下代码进行了双重检查:
func TestIntSize(t *testing.T) {
const PtrSize = 32 << uintptr(^uintptr(0)>>63)
fmt.Println(runtime.GOOS, runtime.GOARCH)
fmt.Println(strconv.IntSize, PtrSize)
}
它返回:
darwin amd64
64 64
我做错了什么?
英文:
given the following function:
func convertValue(contents string) (int, error) {
return strconv.Atoi(contents)
}
when I run the following test
var convertValues = []struct {
contents string
value int
}{
{"9223372036854775807", math.MaxInt64},
{"−9223372036854775808", math.MinInt64},
}
func TestConvertValue(t *testing.T) {
for _, values := range convertValues {
value, err := convertValue(values.contents)
if err != nil {
t.Error("Expecting", values.value, "but got error", err.Error())
}
if value != values.value {
t.Error("Expecting ", values.value, ", but got ", value)
}
}
}
it works for MaxInt64, but not for MinInt64. I'm running this on a MacBookPro, so it's running in 64bit. I have double checked this with the following
func TestIntSize(t *testing.T) {
const PtrSize = 32 << uintptr(^uintptr(0)>>63)
fmt.Println(runtime.GOOS, runtime.GOARCH)
fmt.Println(strconv.IntSize, PtrSize)
}
and it returned
darwin amd64
64 64
What am I doing wrong?
答案1
得分: 1
切换到strconv.ParseInt并明确使用int64作为类型似乎有所帮助。我还遇到了MinInt64字符串中的破折号字符的问题,这可能只是在我的一端,但值得检查并确保它是基本的ASCII字符,而不是某种Unicode破折号。
英文:
https://play.golang.org/p/FtytYJkHSc
Switching to strconv.ParseInt and explicitly using int64 as the type seemed to help. I also had an issue with the dash character in your MinInt64 string, that might just be on my end, but worth checking and making sure it is the basic ASCII character not some kind of Unicode dash.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论