golang将math.MinInt64字符串转换为int失败

huangapple go评论75阅读模式
英文:

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
}{
	{&quot;9223372036854775807&quot;, math.MaxInt64},
	{&quot;−9223372036854775808&quot;, math.MinInt64},
}

func TestConvertValue(t *testing.T) {
	for _, values := range convertValues {
		value, err := convertValue(values.contents)
		if err != nil {
			t.Error(&quot;Expecting&quot;, values.value, &quot;but got error&quot;, err.Error())
		}

		if value != values.value {
			t.Error(&quot;Expecting &quot;, values.value, &quot;, but got &quot;, 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 &lt;&lt; uintptr(^uintptr(0)&gt;&gt;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.

huangapple
  • 本文由 发表于 2016年1月10日 07:13:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/34700039.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定