flagext

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 15, 2018 License: MIT Imports: 3 Imported by: 43

README

flagext GoDoc Go Report Card

Implementations of the flag.Value interface to extend the flag package

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Choice

func Choice(selection *string, choices ...string) flag.Value

Choice implements flag.Value. Pass directly into flag.Var. flag.Var sets selection to the value of a command line flag if it is among the choices. If the flag value is not among the choices, it returns an error.

Example
package main

import (
	"flag"
	"fmt"
	"io/ioutil"

	"github.com/carlmjohnson/flagext"
)

func main() {
	// Bad flag
	{
		fs := flag.NewFlagSet("ExampleChoice", flag.ContinueOnError)
		fs.SetOutput(ioutil.Discard)
		var mode string
		fs.Var(flagext.Choice(&mode, "a", "b"), "mode", "mode to run")

		err := fs.Parse([]string{"-mode", "c"})
		fmt.Println(err) // produces error
	}
	// Good flag
	{
		fs := flag.NewFlagSet("ExampleChoice", flag.ContinueOnError)
		var mode string
		fs.Var(flagext.Choice(&mode, "x", "y"), "mode", "mode to run")

		fs.Parse([]string{"-mode", "x"})
		fmt.Println(mode) // mode is x
	}
	// Default value
	{
		fs := flag.NewFlagSet("ExampleChoice", flag.ContinueOnError)
		mode := "none"
		fs.Var(flagext.Choice(&mode, "yes", "no"), "mode", "mode to run")
		fs.Parse([]string{})
		fmt.Println(mode) // mode is none
	}
}
Output:

invalid value "c" for flag -mode: "c" not in a, b
x
none

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL