Handling Command-Line Input and Output

Tutorial 4 of 5

Handling Command-Line Input and Output in Go

1. Introduction

In this tutorial, we will learn how to handle command-line arguments in Go programming language. Command-line arguments are parameters provided to a program when it is invoked. They are common in programming to provide flexibility and control to the user.

By the end of this tutorial, you'd be able to write programs that accept and utilize command-line arguments.

Prerequisites

  • Familiarity with Go programming language
  • Basic understanding of command-line interfaces

2. Step-by-Step Guide

In Go, command-line arguments are accessed using the os.Args variable in the os package. This variable is a slice of strings, where each string is an argument provided to the program.

The first element in this slice, os.Args[0], is the name of the program itself. The actual command-line arguments start from os.Args[1].

Best Practices and Tips

  • Always check the length of os.Args before accessing its elements to avoid "index out of range" errors.
  • Usage of flag package can simplify command-line argument parsing.

3. Code Examples

Example 1: Basic Command-Line Argument Parsing

package main

import (
    "fmt"
    "os"
)

func main() {
    // Print the name of the program
    fmt.Println("Program:", os.Args[0])

    // Print the command-line arguments
    for i, arg := range os.Args[1:] {
        fmt.Printf("arg %d: %s\n", i+1, arg)
    }
}

In this program, we first print the name of the program, which is os.Args[0]. Then we print each command-line argument. If you run this program with arguments, you will see them printed out.

Example 2: Checking the Number of Arguments

package main

import (
    "fmt"
    "os"
)

func main() {
    if len(os.Args) < 2 {
        fmt.Println("No arguments provided.")
    } else {
        fmt.Println("Arguments:", os.Args[1:])
    }
}

In this program, we first check if any arguments were provided. If not, we print a message. Otherwise, we print the arguments.

4. Summary

In this tutorial, we learned how to handle command-line arguments in Go. We learned that os.Args is a slice that contains the arguments, starting with the program name at index 0.

For further learning, you can explore the flag package in Go which provides more advanced command-line argument parsing.

5. Practice Exercises

  1. Write a program that prints the number of arguments provided.
  2. Write a program that accepts a number as an argument and prints its square.
  3. Write a program that accepts multiple words as arguments and prints them in reverse order.

Solutions

  1. Print number of arguments:
package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Println(len(os.Args) - 1)
}

This program prints the number of arguments by printing the length of os.Args minus one (to exclude the program name).

  1. Square a number:
package main

import (
    "fmt"
    "os"
    "strconv"
)

func main() {
    if len(os.Args) < 2 {
        fmt.Println("Please provide a number.")
        return
    }

    num, err := strconv.Atoi(os.Args[1])
    if err != nil {
        fmt.Println("Invalid number.")
        return
    }

    fmt.Println(num * num)
}

This program converts the first argument to an integer and squares it. If no argument is provided, or if the argument is not a valid number, it prints an error message.

  1. Print words in reverse order:
package main

import (
    "fmt"
    "os"
)

func main() {
    for i := len(os.Args) - 1; i > 0; i-- {
        fmt.Println(os.Args[i])
    }
}

This program prints the arguments in reverse order by iterating over os.Args in reverse.