Question

Can anyone explain flags in Go?

flag.Parse()
var omitNewline = flag.Bool("n", false, "don't print final newline")
Was it helpful?

Solution

See http://golang.org/pkg/flag/ for a full description.

The arguments for flag.Bool are (name string, value bool, usage string)

name is the argument to look for, value is the default value and usage describes the flag's purpose for a -help argument or similar, and is displayed with flag.Usage().

For more detailed example check here

OTHER TIPS

flag is used to parse command line arguments. If you pass "-n" as a command line argument, omitNewLine will be set to true. It's explained a bit farther in the tutorial :

Having imported the flag package, line 12 creates a global variable to hold the value of echo's -n flag. The variable omitNewline has type *bool, pointer to bool.

flags are a common way to specify options for command-line programs.

package main

import (
  "flag"
  "fmt"
)

var (
  env *string
  port *int
)

// Basic flag declarations are available for string, integer, and boolean options.
func init() {
  env = flag.String("env", "development", "a string")
  port = flag.Int("port", 3000, "an int")
}

func main() {

  // Once all flags are declared, call flag.Parse() to execute the command-line parsing.
  flag.Parse()

  // Here we’ll just dump out the parsed options and any trailing positional 
  // arguments. Note that we need to dereference the points with e.g. *evn to 
  // get the actual option values.
  fmt.Println("env:", *env)
  fmt.Println("port:", *port)

}

Run Programs:

go run main.go

Try out the run program by first giving it without flags. Note that if you omit flags they automatically take their default values.

go run command-line-flags.go --env production --port 2000

If you provide a flag with specified value then default will overwrite by passed one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top