Getting Started with Command-Line Flags in Go
Go, also known as Golang, is a statically typed, compiled programming language that has gained popularity for its simplicity, efficiency, and powerful features. One of the key features of Go is its support for command-line flags, which allows developers to easily accept and parse command-line arguments in their applications.
Command-line flags are a common way to provide configuration options and parameters to a program. In Go, the flag
package provides a simple and straightforward way to work with command-line flags. This package allows you to define, parse, and access command-line flags in your Go programs.
Declaring Flags
To declare a command-line flag in Go, you can use the flag.Type()
functions, where Type
is the data type of the flag. For example, to declare a string flag, you would use flag.String()
:
var name = flag.String("name", "John Doe", "Your name")
This declares a string flag with the name "name", a default value of "John Doe", and a usage description of "Your name".
You can also declare flags for other data types, such as int
, bool
, and float64
, using the corresponding flag.Type()
functions.
Parsing Flags
After declaring the flags, you need to parse them using the flag.Parse()
function. This function will read the command-line arguments and assign the values to the corresponding flag variables.
func main() {
flag.Parse()
fmt.Println("Name:", *name)
}
When you run the program with the -name
flag, the value will be assigned to the name
variable, which you can then use in your program.
$ go run main.go -name "Alice"
Name: Alice
Flag Types and Validation
The flag
package in Go supports a variety of flag types, including string
, int
, bool
, and float64
. Each flag type has its own set of validation rules, which can be used to ensure that the input values are valid.
For example, you can use the flag.IntVar()
function to declare an integer flag and specify a range of valid values:
var age = flag.Int("age", 30, "Your age (must be between 18 and 100)")
In this example, the age
flag must be an integer between 18 and 100.
By using the appropriate flag types and validation rules, you can ensure that your command-line flags are used correctly and that your program behaves as expected.