background
command-line flag is used in command-line programs. For example, in wc -l
the -l
is a command-line flag. Go provides a flag package supporting basic command-line flag parsing.
Basic flag declarations are available for string, integer, and boolean options.
package main
import (
"flag"
"fmt"
)
func main() {
wordPtr := flag.String("word", "foo", "a string")
numbPtr := flag.Int("numb", 42, "an int")
forkPtr := flag.Bool("fork", false, "a bool")
var svar string
flag.StringVar(&svar, "svar", "bar", "a string var")
flag.Parse()
fmt.Println("word:", *wordPtr)
fmt.Println("numb:", *numbPtr)
fmt.Println("fork:", *forkPtr)
fmt.Println("svar:", svar)
fmt.Println("tail:", flag.Args())
}
check the code above, wordPtr := flag.String("word", "foo", "a string")
created a flag of word
, the default value of word is “foo”, and the “a string” in the 3rd parameter is a remark.
So we can use the word
flag in command line like ./main.go -word="this is a string"
, and then grant the value to the wordPtr.