Access command-line arguments in Go by reading the os.Args slice, where index 0 is the program name and index 1+ are user inputs.
Access command-line arguments in Go using the os.Args slice, where index 0 is the program name and subsequent indices hold the arguments.
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) > 1 {
fmt.Println("First argument:", os.Args[1])
}
}
Run the program with go run main.go hello to see "First argument: hello" printed.
When you run a Go program from the terminal, any extra words you type after the program name are stored in a list called os.Args. The first item in this list is always the name of your program itself, and everything else follows in order. Think of it like a numbered list of instructions you gave the program when you started it.