Go (Golang) / Building CLI Applications in Go
Handling Command-Line Arguments and Flags
This tutorial will guide you through the process of handling command-line arguments and flags in Go. You will learn how to parse and process user-provided data to make your CLI ap…
Section overview
5 resourcesExplores how to build command-line applications using Go.
Handling Command-Line Arguments and Flags in Go
1. Introduction
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.
Goals
- Understand command-line arguments and flags
- Learn how to parse and process command-line arguments and flags in Go
Prerequisites
- Basic understanding of Go programming
- An installed version of Go to run the examples
2. Step-by-Step Guide
Command-Line Arguments
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], ...).
Flags
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").
3. Code Examples
Example 1: Accessing Command-Line Arguments
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.
Example 2: Using Flags
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.
4. Summary
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.
5. Practice Exercises
- Write a Go program that accepts two command-line arguments and prints their sum.
- Write a Go program that uses flags to accept a user's name and favorite color, and then prints a message using these details.
Solutions
- Sum of Two Arguments
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)
}
- User's Details with Flags
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!
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article