How do I access command-line arguments in Go? They\'re not passed as arguments to main.
A complete program, possibly created by linking m
Quick Answer:
package main
import ("fmt"
"os"
)
func main() {
argsWithProg := os.Args
argsWithoutProg := os.Args[1:]
arg := os.Args[3]
fmt.Println(argsWithProg)
fmt.Println(argsWithoutProg)
fmt.Println(arg)
}
Test: $ go run test.go 1 2 3 4 5
Out:
[/tmp/go-build162373819/command-line-arguments/_obj/exe/modbus 1 2 3 4 5]
[1 2 3 4 5]
3
NOTE:
os.Argsprovides access to raw command-line arguments. Note that the first value in this slice is the path to the program, andos.Args[1:]holds the arguments to the program. Reference