Go (Golang) / File Handling and I/O Operations

Handling Command-Line Input and Output

This tutorial will cover handling command-line arguments in Go. We'll use the 'os' package to access arguments provided at the command line when running a program.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Explains how to read and write files, work with directories, and handle I/O operations in Go.

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.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Backlink Checker

Analyze and validate backlinks.

Use tool

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

Use tool

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI 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 article

AI 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 article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help