flag用于解析命令行参数

目录

语法

-flag //只支持bool -flag=x //都支持 -flag x //支持非bool

bool类型可以为:1,0,t,f,T,F,true,false,True,False,TRUE,FALSE

flag定义参数

  • flag.String()等flag.Xxx()方法,flag该方式返回一个指针
  • flag.XxxVar()方法将flag参数绑定到一个变量
  • flag.Var()方法绑定自定义类型,自定义类型需要实现Value()接口

flag.Parse()

解析命令行参数到定义的flag

获取非flag参数

flag.Args() flag.Arg(i)

绑定自定义的flag参数

绑定自定义的flag参数需要实现标准库里的Value接口。

// Value is the interface to the dynamic value stored in a flag.
// (The default value is represented as a string.)
//
// If a Value has an IsBoolFlag() bool method returning true,
// the command-line parser makes -name equivalent to -name=true
// rather than using the next command-line argument.
//
// Set is called once, in command line order, for each flag present.
// The flag package may call the String method with a zero-valued receiver,
// such as a nil pointer.
type Value interface {
	String() string
	Set(string) error
}

// Getter is an interface that allows the contents of a Value to be retrieved.
// It wraps the Value interface, rather than being part of it, because it
// appeared after Go 1 and its compatibility rules. All Value types provided
// by this package satisfy the Getter interface.
type Getter interface {
	Value
	Get() interface{}
}

示例

package main

import (
	"flag"
	"fmt"
)

type human struct {
	Name string
}

func (h *human) String() string {
	return h.Name
}

func (h *human) Set(val string) error {
	h.Name = val
	return nil
}

var people human

func main() {
	flag.Var(&people, "h", "xxxxxxxxxxxxxxxxx")
	flag.Parse()

	fmt.Println(people)
}

// output
// $ go run main.go -h pytimer
// {pytimer}