Tuesday 5 October 2021

Command Line arguments in Golang

So in this article we're about to cover the Command-Line Arguements in Golang, How to get the arguments and parse those arguments into application...

Let’s start writing some programs in Go that will allow us to pass command-line arguments while running a Go program. It's really easy and allows us to pass custom arguments while running a Go program. We will create our custom arguments as well.


Working with Command-Line(CLI) arguments

How to pass the Command-Line arguments? Simply use those in a space-separated way with program name.

./toolname arg1 arg2 arg3


1. The “os” Package of Golang

The os package contains the args which is a array of arguments, that helps use to get the unlimited amount of command-line arguement while running the program/binary. Let’s see our first argument, the program name which you don’t need to pass at all.


The following code will print the program name in the command line.
OUTPUT:



2. How to Get Number of CLI Arguments Used in a Program

We can get the total number of arguments passed through the command-line easily. To acheive that, we uses len() function.

Here is the code that prints the length of total arguments passed to a program.
OUTPUT:



3. Iterating over command-line arguments.

To iterate over the arguments passed via the command line, we will loop over the args variable which holds os.Args array.

See Below to know how to do that
OUTPUT:



4. The “flag” package

To create flags, we'll use a package called flag(inbuilt). We will create a simple login mechanism as an example.

Below is the code for the login system.
OUTPUT:



5. Inserting wrong values in login CLI

Inserting wrong values will give you an error and provide you the correct usage of those flags. For example, if you input a number while using a string flag, an error will be thrown and the correct usage will be printed to the console.
OUTPUT:

Labels: , ,

0 Comments:

Post a Comment

If have any queries lemme know

Subscribe to Post Comments [Atom]

<< Home