Ad space (banner)
๐ŸนGo Lessons
Lesson 55 / 68

Reading Command-Line Arguments

In this lesson you will learn how to read command-line arguments in Go, so values can be passed in from outside when the program runs. This is for anyone searching for "Go os.Args how to use".

The string slice os.Args holds the command-line arguments (os.Args[0] is the path of the executable itself).

The sample code checks that enough arguments were supplied with len(os.Args) > 2, then prints os.Args[1] as the name and os.Args[2] as the age. It also serves as the basis of simple automation scripts that branch on the values supplied at run time.

A common stumbling block for beginners is reaching for an argument without checking how many were passed, which causes an error. You need to check the count with len(os.Args) first.

In real-world development, for a serious CLI tool the flag package makes named options much easier to handle.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)