BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Command-line Arguments

Go 1.23

Learn how to access and process raw command-line arguments in Go using `os.Args`. This example explains the structure of the arguments slice and how to distinguish between the program name and user-provided arguments.

Code

package main

import (
    "fmt"
    "os"
)

func main() {
    // os.Args provides access to raw command-line arguments.
    // Note that the first value in this slice is the path to the program,
    // and os.Args[1:] holds the arguments to the program.
    argsWithProg := os.Args
    argsWithoutProg := os.Args[1:]

    // You can get individual args with normal indexing.
    // Note: This will panic if not enough arguments are provided.
    if len(os.Args) > 3 {
        arg := os.Args[3]
        fmt.Println(arg)
    }

    fmt.Println(argsWithProg)
    fmt.Println(argsWithoutProg)
}

Explanation

Command-line arguments allow users to parameterize program execution. Go provides raw access to these via os.Args, a slice of strings containing the full command line.

Important details about os.Args:

  • Index 0: os.Args[0] is always the path/name of the program itself. The actual user arguments start at index 1.
  • Manual Parsing: While os.Args gives you everything, manually parsing flags and options (like --help or -v) is error-prone.

For simple scripts, checking len(os.Args) is fine. For anything more complex, use the flag package or a robust CLI framework like Cobra.

Code Breakdown

11
argsWithProg stores the complete os.Args slice, including the program path at index 0. This is useful when you need to know how the program was invoked.
12
os.Args[1:] creates a new slice containing only the actual arguments, excluding the program name. This slice notation means "from index 1 to the end".
16-18
Safety check before accessing a specific argument. We verify that at least 4 arguments exist (indices 0-3) before trying to access os.Args[3]. Without this check, accessing a non-existent index would cause a runtime panic.
21-22
Printing both slices to demonstrate the difference. argsWithProg includes the program path, while argsWithoutProg contains only the user-provided arguments.