Go Command-Line Arguments Parsing

Introduction

When we invoke a command on the terminal, we can pass that command arguments.

We've seen this with the go command:

go run myfile.go 

run and myfile.go are arguments. We can also pass flags to a command:

go run -v myfile.go 

The flag package allows us to parse arguments and flags sent to our program.

Here's an example program that generates a number between 0 and 6.

We can change the max value by sending a flag ( -max=100) to the program:

package main /*from ww w  .  j  a va2  s  .c om*/

import ("fmt";"flag";"math/rand") 

func main() { 
    // Define flags 
    maxp  := flag.Int("max", 6, "the max value") 
    // Parse 
    flag.Parse() 
    // Generate a number between 0 and max 
    fmt.Println(rand.Intn(*maxp)) 
} 

Any additional non-flag arguments can be retrieved with flag.Args(), which returns a []string.




PreviousNext

Related