Command-line arguments are parameters provided to a program at the time of execution. Flags are a type of command-line argument used to modify the behavior of an application. This tutorial aims to introduce you to handling command-line arguments and flags in Go.
In Go, command-line arguments are accessed via the os.Args
variable which is an array, with the first element of the array (os.Args[0]
) being the path to the executed program. The actual arguments start from index 1 (os.Args[1], os.Args[2], ...
).
Go's standard library provides a flag
package to handle command-line options. Using this package, you can define boolean flags, integer flags, string flags, and more. The basic syntax is flag.Var(&variable, "flagname", default_value, "help message")
.
package main
import (
"fmt"
"os"
)
func main() {
args := os.Args
fmt.Println(args) // print all arguments
fmt.Println(args[1]) // print first argument
}
In this example, os.Args
is an array that contains all command-line arguments. args[1]
gives us the first argument.
package main
import (
"flag"
"fmt"
)
func main() {
name := flag.String("name", "Guest", "Your name")
age := flag.Int("age", 25, "Your age")
flag.Parse()
fmt.Printf("Hello %s, you are %d years old!\n", *name, *age)
}
Here, we define two flags: name
and age
. The flag.Parse
function is used to read the command-line arguments and assign their values to the related flag variables.
In this tutorial, you've learned how to handle command-line arguments and flags in Go. You've seen how to access command-line arguments using os.Args
and how to parse flags using the flag
package.
For further reading and practice, check out the official Go documentation for the os
and flag
packages.
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
arg1, _ := strconv.Atoi(os.Args[1])
arg2, _ := strconv.Atoi(os.Args[2])
sum := arg1 + arg2
fmt.Printf("The sum is: %d\n", sum)
}
package main
import (
"flag"
"fmt"
)
func main() {
name := flag.String("name", "John Doe", "Your name")
color := flag.String("color", "blue", "Your favorite color")
flag.Parse()
fmt.Printf("Hello %s, your favorite color is %s!\n", *name, *color)
}
Keep practicing with different types of arguments and flags to gain more confidence!