Handling Command-Line Arguments and Flags

Tutorial 2 of 5

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

  1. Write a Go program that accepts two command-line arguments and prints their sum.
  2. 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

  1. 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)
}
  1. 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!