The error is expected as we are looping over a slice of strings, which are the arguments stored in os.Args, and there are only three arguments; the first argument being the name of the program itself, and the “foo” and “bar” supplied by us in the terminal. This can be easily fixed by finding the number of strings in os.Args, by doing the following.

Using the flag package

Using the flag package, we can take flags entered at the time of running the program and parse them, and hence we can do some more action with the flags/arguments that we pass. The flag.StringVar function takes the following input:

StringVar func(p *string, name string, value string, usage string)

StringVar defines a string flag with specified name, default value, and usage ring. The > argument p points to a string variable in which to store the value of the flag.

StringVar is not the only thing that could be used; you could also use IntVar, Float64 and so on.

Please note that you should never do this, as it is really simple to disassemble the program and extract the plain text password even though the disassembly of Go is arguably more messy than of a C program, as demonstrated below.

Conclusion

Compared to other implementations in other languages, like argparse in Python, the flag package might not be a very advanced or intuitive one. For simple and small programs, it might get the job done. There are some obvious shortcomings, for example the flag package does not support mandatory or required flags (meaning the flag must be specified explicitly).

Hence, you might want to check out more extensive implementations like cli and Cobra. Cobra is used in many projects written in Go like Hugo and Kubernetes.