Command-Line Flags in Go
Golang Concepts
Go: Command-Line Flags
Go provides a simple way to parse command-line flags using the flag
package.
How to define and parse command-line flags in Go
Here's an example of how to define and parse command-line flags in Go:
package main
import (
"flag"
"fmt"
)
func main() {
// Define a flag "name" with a default value "World" and a description
name := flag.String("name", "World", "the name to greet")
// Parse the command-line arguments
flag.Parse()
// Print the personalized greeting
fmt.Printf("Hello, %s!\n", *name)
}
This code defines a flag -name
with a default value World
and a description using the flag.String
function. It then calls flag.Parse
to parse the command-line arguments and set the value of the name variable. Finally, it prints a personalized greeting using the value of the name variable.
You can define other types of flags using functions like flag.Bool
, flag.Int
, and flag.Float64
, depending on the type of data you want to parse.
Parse a boolean flag in Go
Here's an example of how to define and parse a boolean flag:
package main
import (
"flag"
"fmt"
)
func main() {
// Define a boolean flag "loud" with a default value false and a description
loud := flag.Bool("loud", false, "whether to greet loudly")
// Parse the command-line arguments
flag.Parse()
// Print the personalized greeting, optionally loud
if *loud {
fmt.Printf("HELLO, %s!\n", *name)
} else {
fmt.Printf("Hello, %s!\n", *name)
}
}
This code defines a boolean flag -loud
with a default value false and a description using the flag.Bool
function. It then calls flag.Parse
to parse the command-line arguments and set the value of the loud variable. Finally, it prints a personalized greeting either normally or loudly depending on the value of the loud flag.
I hope that it helps you get started with working with command-line flags in Go! Let me know if you have any more questions.