↓ Skip to main content
Go

GoLang: Program Banner

·2 mins

In the last blog I talked about command line arguments os.Args[]. In this I will try and create a sample banner program that shall

  • Take 3 arguments
  • n - Number of times a message has to be repeated.
  • m - The message that needs to be shown.
  • d - If debug message needs to be shown.

I am going to use the flags package.

Source code is available here — https://github.com/samarthya

Defining: Banner
#

The package flag has the extended capability of parsing the flags.

Define Flags
#

Variant one
#

var times = flag.Int("n", 1, "number of times the message needs to be displayed")
var msg = flag.String("m", "", "the message that needs to be printed")
var dbg = flag.Bool("d", false, "to debug or not")
A good reference available here.

You can also define flags using

var nTimes int

func init() {
	flag.IntVar(&nTimes, "n", 1, "number of times the message needs to be displayed")
}

After all flags are defined you must call, to parse the command line into flags. If you miss this one you might not get the desired results. (Give it a try)

// Must be called after all flags are defined and before flags are accessed within the program
flag.Parse()

How to pass values to these flags?

-flag
-flag=x
-flag x

Build
#

go build src/cmdline/cmd.go

This will produce the binary - cmd.

Run the cmd
#

./cmd
  -d    to debug or not
  -m string
        the message that needs to be printed
  -n int
        number of times the message needs to be displayed (default 1)
./cmd -n 2 -m="Why is world round?"

--- Command line Program ---

 >> Why is world round?

 >> Why is world round?
./cmd -n 2 -m="Why is world round?" -d=true
DBG: Number of Arguments: 5
--- Command line Program ---

 >> Why is world round?

 >> Why is world round?
./cmd -m="Why is world round?" -n=3  -d=true
DBG: Number of Arguments: 4
--- Command line Program ---

 >> Why is world round?

 >> Why is world round?

 >> Why is world round?
Author
Samarthya
Engineer, learner, tinkerer. This is my trophy shelf of everyday work and leisure.

Related

GoLang: Command line arguments

·1 min
Reading the golang official documentation is fun, today I saw the Variables in package os var Args []string It allows you to hold command line arguments and a simple main program that can help you validate this.

Files: GoLang

·2 mins
In the last blog, I tried reading a file in GoLang. My repository in GitHub has all the code that I write (link) Now, I will extend the same program to write to the same file.

Files: GoLang

·4 mins
Learning a new syntax and the libraries is always a task, and the only way forward is gradual. In this blog I will try to create a small program to read a text file and will keep updating the program to include more sophistication