The flag package is a convenient package for parsing command line flags.
import "flag"
When binding to a variable with XxxVar () of init () described later, prepare a variable to store the flag.
var boolFlag bool
var intFlag int
var strFlag string
If it is not bound to a variable with XxxVar () of init () described later, it becomes a pointer.
boolPtr := flag.Bool("b", false, "Example of boolean value")
intPtr := flag.Int("i", 0, "Example for numerical values")
strPtr := flag.String("s", "", "Example for strings")
init () is executed before main () is called. The value of the flag specified in the variable by flag.Parse () described in main is entered, but the value is not yet entered in the variable at the time of init. Therefore, here, the behavior is only to reserve a pointer for storing the value of the flag. Bind to a variable with XxxVar (). Describe the pointer of the variable, the name of the flag, the default value, and the explanation of how to use it in the argument.
func init() {
flag.BoolVar(&boolFlag, "b", false, "Specify a boolean value")
flag.IntVar(&intFlag, "i", 0, "Specify a numeric value")
flag.StringVar(&strFlag, "s", "", "Specify the value of the string")
}
Calling flag.Parse () parses the command line argument flags and binds them to variables.
flag.Parse()
After that, the value of the flag can be obtained from the variable.
#No flag specified
go run flagsample.go
#With flag specified
go run flagsample.go -b
go run flagsample.go -b -i=1 -s=a
#Compile the program and
go build flagsample.go
#Then run the binary.
./flagsample -b -i=1 -s=a
How to write when defining outside a function
package main
import (
"flag"
"fmt"
)
var boolFlag bool
var intFlag int
var strFlag string
func init() {
flag.BoolVar(&boolFlag, "b", false, "Example of boolean value")
flag.IntVar(&intFlag, "i", 0, "Example for numerical values")
flag.StringVar(&strFlag, "s", "", "Example for strings")
}
func main() {
flag.Parse()
fmt.Println(boolFlag)
fmt.Println(intFlag)
fmt.Println(strFlag)
}
How to write defined in a function
package main
import (
"flag"
"fmt"
)
func main() {
boolPtr := flag.Bool("b", false, "Example of boolean value")
intPtr := flag.Int("i", 0, "Example for numerical values")
strPtr := flag.String("s", "", "Example for strings")
flag.Parse()
fmt.Println(*boolPtr)
fmt.Println(*intPtr)
fmt.Println(*strPtr)
}
-Go language learned with sample: Command-Line Flags
Recommended Posts