Go flag.Int: Command-Line Integer Flags Explained
The 'flag.Int()' function is a helper function provided by the Go standard library's 'flag' package that allows you to define a command-line flag that should be interpreted as an integer value.
It takes four arguments:
- A pointer to an integer variable that will hold the value of the flag after it has been parsed.
- The name of the flag, which should start with a single hyphen (-) and should not include any spaces.
- The default value of the flag, which will be used if the flag is not set explicitly on the command line.
- A help message that will be displayed to the user if they pass the '-h' or '--help' flag.
Here's an example usage:
package main
import (
"flag"
"fmt"
)
func main() {
var foo int
flag.IntVar(&foo, "foo", 42, "an integer flag")
flag.Parse()
fmt.Println("foo:", foo)
}
In this example, the '-foo' flag is defined with a default value of 42. If the user runs the program with no arguments, the value of 'foo' will be 42. If they run it like this:
$ ./myprogram -foo=99
Then the value of 'foo' will be set to 99.
原文地址: https://www.cveoy.top/t/topic/niDn 著作权归作者所有。请勿转载和采集!