Integer arguments with leading zeros are parsed as octal by flag.IntVar or flag.Int

王林
Release: 2024-02-08 21:10:08
forward
598 people have browsed it

带有前导零的整数参数由 flag.IntVar 或 flag.Int 解析为八进制

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.

Question content


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)
}
Copy after login

When I run this command:

./a -i 10
10
Copy after login

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
Copy after login

Is this a bug?


Solution


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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!