Go programming example [command line flags Flags]

read catalog

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

For example, wc -lin , the -lis a command-line flag.

// command-line-flags.go
package main

// Go 提供了一个 `flag` 包,支持基本的命令行标志解析。
// 我们将用这个包来实现我们的命令行程序示例。
import (
	"flag"
	"fmt"
)

func main() {
    
    

	// 基本的标记声明仅支持字符串、整数和布尔值选项。
	// 这里我们声明一个默认值为 `"foo"` 的字符串标志 `word`
	// 并带有一个简短的描述。这里的 `flag.String` 函数返回一个字
	// 符串指针(不是一个字符串值),在下面我们会看到是如何
	// 使用这个指针的。
	wordPtr := flag.String("word", "foo", "a string")

	// 使用和声明 `word` 标志相同的方法来声明 `numb` 和 `fork` 标志。
	numbPtr := flag.Int("numb", 42, "an int")
	boolPtr := flag.Bool("fork", false, "a bool")

	// 用程序中已有的参数来声明一个标志也是可以的。注
	// 意在标志声明函数中需要使用该参数的指针。
	var svar string
	flag.StringVar(&svar, "svar", "bar", "a string var")

	// 所有标志都声明完成以后,调用 `flag.Parse()` 来执行
	// 命令行解析。
	flag.Parse()

	// 这里我们将仅输出解析的选项以及后面的位置参数。注意,
	// 我们需要使用类似 `*wordPtr` 这样的语法来对指针解引用,从而
	// 得到选项的实际值。
	fmt.Println("word:", *wordPtr)
	fmt.Println("numb:", *numbPtr)
	fmt.Println("fork:", *boolPtr)
	fmt.Println("svar:", svar)
	fmt.Println("tail:", flag.Args())
}

Before testing this program, it is best to compile this program into a binary file and then run this program.

[root@bogon test]# go run main.go 
word: foo
numb: 42
fork: false
svar: bar
tail: []
[root@bogon test]# 

Note that if you omit a flag, the flag's value is automatically set to its default value.

[root@bogon test]# go run main.go -word=opt
word: opt
numb: 42
fork: false
svar: bar
tail: []
[root@bogon test]# 

Trailing positional arguments can appear after any flags.

[root@bogon test]# go run main.go -word=opt a1 a2 a3
word: opt
numb: 42
fork: false
svar: bar
tail: [a1 a2 a3]
[root@bogon test]# 

Note that
the flag package requires all flags to appear before positional arguments (otherwise, the flag will be parsed as a positional argument).

[root@bogon test]# go run main.go -word=opt a1 a2 a3 -numb=7
word: opt
numb: 42
fork: false
svar: bar
tail: [a1 a2 a3 -numb=7]
[root@bogon test]# 

Use -hthe or --helpflags to get automatically generated help text for this command-line program.

[root@bogon test]# go run main.go -h
Usage of /tmp/go-build2106597789/b001/exe/main:
  -fork
        a bool
  -numb int
        an int (default 42)
  -svar string
        a string var (default "bar")
  -word string
        a string (default "foo")
[root@bogon test]# 

If you supply a flag that was not specified using the flags package, the program outputs an error message and displays the help text again.

[root@bogon test]# go run main.go -wat
flag provided but not defined: -wat
Usage of /tmp/go-build2586570688/b001/exe/main:
  -fork
        a bool
  -numb int
        an int (default 42)
  -svar string
        a string var (default "bar")
  -word string
        a string (default "foo")
exit status 2
[root@bogon test]# 

Guess you like

Origin blog.csdn.net/weiguang102/article/details/129877542