Command line flags in Golang

Command line flags helps to pass the value from command line itself when running the program. If you are a C/C++ programmer in unix platform then you must aware of getopt. Command line flags in golang is similar to getopt in C. 

This facility provided in golang with the help of a package called flag.


Command line flags support for three data types. Those are

  1. Integer (int)
  2. Boolean (bool)
  3. String (String)
Below is the example program and its output

PROGRAM:

package main
import (
"flag"
"fmt"
)
func main() {
/* define int, string and bool type flags, it return pointer value */
agePtr := flag.Int("age", 18, "age as integer")
namePtr := flag.String("name", "John", "name as string")
availPtr := flag.Bool("avail", false, "availability boolean")
/* Parse all defined flags */
flag.Parse()
/* since flag return pointer value, dereference it to get value */
fmt.Println("Name:", *namePtr, " Age:", *agePtr, " Availability:", *availPtr)
}

Run:
go run flag.go



OUTPUT:

./flag -name=Bruce -age=35 -avail
Name: Bruce  Age: 35  Availability: true



./flag -name=Mark -age=26
Name: Mark  Age: 26  Availability: false



./flag
Name: John  Age: 18  Availability: false




flag declaration take three arguments flagname, default value and flag name description

    agePtr := flag.Int("age", 18, "age as integer")

This means it declare integer flag with flag name as 'age' its default value '18' and description 'age as integer'. It return pointer value so agePtr has to be de-referenced when using as value.


There is one more way to declare command line flag in golang example program below. 

PROGRAM:
package main

import (
"flag"
"fmt"
)

func main() {
var (
age int
name string
avail bool
)

flag.IntVar(&age, "age", 20, "age as integer")
flag.StringVar(&name, "name", "Peter", "name as string")
flag.BoolVar(&avail, "avail", false, "avail as boolean")

/* Parse all defined flags */
flag.Parse()

/* value type so dereferencing not needed */
fmt.Println("Name:", name, " Age:", age, " Avail:", avail)
}
OUTPUT:
./flag -name=jack -avail -age=31
Name: jack Age: 31 Avail: true


instead of returning flag value as pointer here we can pass a variable and get the the value. 

    flag.StringVar(&name, "name", "Peter", "name as string")
This take four parameters address of variable, name of the flag, default value and flag description


No comments:

Post a Comment