This page looks best with JavaScript enabled

flag

 ·  ☕ 2 min read

flag package

flag package provides types and functions useful for working with command line flags.

installation

flag package is part of standard Go library at flag

usage

Simple usage of flag

  1. var variable_name = flag.Type("flag_name", "initial_value", "help_message")
  2. flag.Type defines the data type of flag flag.String(), Bool(), Int(), etc.
  3. flag_name is used from command line to pass value to flag.
  4. initial_value is used to initialize flag to some default value and help_message is used to provide help information to user.
  5. value of flag will always be pointer by variable_name which is a pointer.
  6. for flag values to be available, we need to call flag.Parse() before using them.

    flag.go

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    
    package main
    
    import (
      "flag"
      "fmt"
    )
    
    func main() {
      var name = flag.String("username", "hello", "username to use to run script")
      flag.Parse()
      fmt.Printf("user is %s\n", *name)
    }
    
    

    terminal

    1
    2
    3
    4
    5
    6
    7
    8
    
    $>go run flag.go --help
    Usage of /tmp/go-build875059667/b001/exe/flag:
    -username string
          username to use to run script (default "hello")
    exit status 2
    
    $> go run flag.go -username=sumit
    user is sumit
    

package source and documentation

https://golang.org/pkg/flag/#pkg-overview


Sumit
WRITTEN BY
Sumit
Gopher


What's on this Page