php editor Yuzai introduced: In the Go language, command line parameters can be parsed through the flag package. When we use flag.IntVar or flag.Int to parse an integer argument with leading zeros, they parse it as octal. This means that if we enter an integer argument starting with 0 on the command line, it will be parsed as an octal number, not a decimal number. This is something to note because sometimes we may want to handle arguments as decimal numbers instead of octal numbers. Therefore, when using the flag package to parse parameters, special attention needs to be paid to how integer parameters with leading zeros are parsed.
I wrote this code:
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) }
When I run this command:
./a -i 10 10
The output is correct.
But why if I run it with 010
, golang will parse 010
as octal (010
== 8
) ?
./a -i 010 i < 9 8
Is this a bug?
Oh, this is a terrible trap.
Is this a bug?
It was intentionally added before Go 1.0.0 in 2011. p>
Flags: Allows input of hexadecimal and octal integer flags.
You can find the full behavior in the documentation for strconv.ParseInt
, but not its use in flag
which is documented.
The above is the detailed content of Integer arguments with leading zeros are parsed as octal by flag.IntVar or flag.Int. For more information, please follow other related articles on the PHP Chinese website!