flag.IntVar或flag.Int解析带有前导零的整数参数时会将其解析为八进制数。

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

Integer argument with a leading zero is parsed as octal by flag.IntVar or flag.Int

问题

我写了这段代码:

package main

import "fmt"
import "flag"

func main() {
	
	var i int
	
	flag.IntVar(&i, "i", 0, "help")
	flag.Parse()

	if i < 9 {
		fmt.Println("i < 9")
	}

	fmt.Println(i)
}

当我运行以下命令时:

./a -i 10

输出是正确的:

10

但是为什么,如果我用 010 运行它,Golang 会将 010 解析为八进制(010 等于 8)?

./a -i 010

输出是:

i < 9
8

这是一个 bug 吗?

英文:

I wrote this code:

package main

import &quot;fmt&quot;
import &quot;flag&quot;

func main() {
	
	var i int
	
	flag.IntVar(&amp;i, &quot;i&quot;, 0, &quot;help&quot;)
	flag.Parse()

	if i &lt; 9 {
		fmt.Println(&quot;i &lt; 9&quot;)
	}

	fmt.Println(i)
}

When I run this command:

./a -i 10
10

the output is correct.

But why, if I run it with 010, does Golang parse 010 as a octal (010 == 8)?

./a -i 010
i &lt; 9
8

Is this a bug?

答案1

得分: 3

哦,这是一个很糟糕的陷阱。

> 这是一个 bug 吗?

这是在 2011 年有意添加的,早于 Go 1.0.0。

> flag:允许在整数标志中输入十六进制和八进制。

你可以在 strconv.ParseInt 的文档中找到完整的行为说明,尽管它在 flag 中的使用没有被记录。

英文:

Oof, that’s a terrible gotcha.

> Is this a bug?

It was added intentionally in 2011, before Go 1.0.0.

> flag: allow hexadecimal and octal input for integer flags.

You can find the full behavior in the documentation for strconv.ParseInt, not that its use in flag is documented.

huangapple
  • 本文由 发表于 2023年5月24日 10:16:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76319698.html
匿名

发表评论

匿名网友

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

确定