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…

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explores 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

  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!

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

Case Converter

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

Use tool

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

Color Palette Generator

Generate color palettes from images.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Fake User Profile Generator

Generate fake user profiles with names, emails, and more.

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