LESSON · 1 OF 20

What os.Args holds

What os.Args holds

When you run a program from the shell, everything you type after the program name is passed in as arguments. Go hands you those in a single place: os.Args, a []string from the os package.

os.Args holds the program name plus every argument, in order. This is a complete program that prints the whole slice:

go
package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Println(os.Args)
}

Build it and run it with a couple of arguments:

text
$ go build -o greet main.go
$ ./greet alice bob
[./greet alice bob]

The first element, os.Args[0], is always the program itself (the path used to invoke it). The real arguments start at index 1, so os.Args[1] is alice and os.Args[2] is bob. The whole slice of arguments without the program name is os.Args[1:].

The shape to memorise

  • os.Args is a []string: program name plus arguments.
  • os.Args[0] is the program, os.Args[1:] are the arguments.
Spin up a fresh environment and practice live.
go · fresh machine · ready in under a minute