Golang flag.FlagSet.Init() function example

package flag

Init sets the name and error handling property for a flag set. By default, the zero FlagSet uses an empty name and the ContinueOnError error handling policy.

Golang flag.FlagSet.Init() function usage example

 package main

 import (
 "flag"
 "os"
 )

 const (
 usage = `programname [--force] file [file ...]

 Will molest the given file.
 Unless force is specified, it will ask the user for permission before molesting...
 `
 )

 func printUsage() {
 os.Stderr.WriteString(usage)
 os.Exit(0)
 }

 func main() {

 force := false

 flagSet := flag.NewFlagSet("", flag.ContinueOnError)

 flagSet.Init("command-line", flag.ContinueOnError) // <-- here
 flagSet.BoolVar(&force, "force", force, "--force is required to force everything down the pipe, without asking")

 if err := flagSet.Parse(os.Args[1:]); err != nil {
 printUsage()
 }

 if len(flagSet.Args()) == 0 {
 printUsage()
 }

 }

Reference :

http://golang.org/pkg/flag/#FlagSet.Init

Advertisement