C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Then: The flag.Int func returns an Int pointer. We access its Int value with the star character.
Copy: We can copy the value from the Int pointer into an Int with an assignment statement. We do this with the "value" local.
Run: We invoke the Go executable and pass the "run" argument to it. We pass the program file name and specify the count argument.
Default: The second argument is the default value for that flag. If Parse() is called and no value is found, 5 will be used.
Golang program that uses flag.Int, command-line argument
package main
import (
"flag"
"fmt"
)
func main() {
// Register Int flag.
count := flag.Int("count", 5, "count of iterations")
// Parse the flags.
flag.Parse()
// Print the argument.
fmt.Println("Argument", *count)
// Get int from the Int pointer.
value := *count
fmt.Println("Value", value)
}
Command line:
C:\Go\bin\Go.exe run C:\programs\file.go -count=20
Output
Argument 20
Value 20
Here: We specify a special "greeting" string, and then uppercase it as the program executes.
Golang program that uses flag.String
package main
import (
"flag"
"fmt"
"strings"
)
func main() {
// A string flag.
greeting := flag.String("greeting", "Hello", "startup message")
flag.Parse()
// Get String.
// ... Uppercase it for emphasis.
value := *greeting
fmt.Println("Program says:", strings.ToUpper(value))
}
Command line:
C:\Go\bin\Go.exe run C:\programs\file.go -greeting=Hey
Output
Program says: HEY
Example command line syntax:
C:\Go\bin\Go.exe run C:\programs\file.go -greeting Hey
Program says: HEY
C:\Go\bin\Go.exe run C:\programs\file.go greeting Hey
Program says: HELLO
C:\Go\bin\Go.exe run C:\programs\file.go GREETING=Hey
Program says: HELLO
Golang program that shows invalid argument
package main
import (
"flag"
"fmt"
)
func main() {
// A string flag.
size := flag.Int("size", 0, "file size")
flag.Parse()
// Print size.
fmt.Println(*size)
}
Command line:
C:\Go\bin\Go.exe run C:\programs\file.go -size=bird
Output
invalid value "bird" for flag -size:
strconv.ParseInt: parsing "bird": invalid syntax
Usage of C:\...\go-build032374134\command-line-arguments\_obj\exe\file.exe:
-size int
file size
exit status 2
Quote: Package flag implements command-line flag parsing.
Flag: golang.org