Golang之flage
来源:互联网 发布:淘宝商品迁徙 编辑:程序博客网 时间:2024/06/07 08:07
golang的flage包提供了对命令行参数的解析。
1. flage提供的几个基本函数
package mainimport ( "flag" "fmt")func main() { //1.参数的名字 2.默认的参数 3.参数详情 name := flag.String("name", "happy", "input into your name") age := flag.Int("age", 23, "your age") sex := flag.Bool("sex", true, "your sex") flag.Parse() fmt.Println("name:", *name) fmt.Println("age:", *age) fmt.Println("vip:", *sex)}
运行程序
***.exe -name haha -age 18 -sex true
输出结果
如果运行程序时不输入参数的话,则输出为默认的参数
另外可以将解析出来的参数绑定到变量上
var Name string flag.StringVar(&Name , "name", "happy", "input into your name") flag.Parse() fmt.Println("name:",Name)
2. 自定义flage
用户可以使用flage.Value()定义一个flage。
flage.Value()的声明如下:
// Var defines a flag with the specified name and usage string. The type and// value of the flag are represented by the first argument, of type Value, which// typically holds a user-defined implementation of Value. For instance, the// caller could create a flag that turns a comma-separated string into a slice// of strings by giving the slice the methods of Value; in particular, Set would// decompose the comma-separated string into the slice.func Var(value Value, name string, usage string) { CommandLine.Var(value, name, usage)}
根据如上描述,我们需要先自定义类型并实现Value 接口:
type Value interface {
String() string
Set(string) error
}
代码如下:
package mainimport ( "flag" "fmt")type flagestring stringfunc (p *flagestring) Set(s string) error { *p = flagestring(s) return nil}func (p *flagestring) String() string { return fmt.Sprintf("%f", *p)}func main() { var Name flagestring //设置默认的参数为 new flage Name.Set("happy") //1.参数变量 2.参数名字 3.参数描述 flag.Var(&Name, "name", "input your name") flag.Parse() fmt.Println("name:", Name)}
运行程序:
***.exe -name gaoxing
运行结果:
3. Arge 和Arges
分别获得所有的参数和某个参数
// Args returns the non-flag command-line arguments.func Args() []string { return CommandLine.args }
// Arg returns the i'th command-line argument. Arg(0) is the first remaining argument// after flags have been processed. Arg returns an empty string if the// requested element does not exist.func Arg(i int) string { return CommandLine.Arg(i)}
阅读全文
2 0
- Golang之flage
- Android Intent 常用的 flage
- 开启golang之旅
- Golang之interface
- Golang之继承模拟
- golang之sqlserver连接
- golang之defer
- Golang之bytes.buffer
- Golang之字符串格式化
- Golang之继承模拟
- GoLang之协程
- Golang之chan/goroutine
- Golang之bytes.buffer
- Golang语言 之网络
- GoLang之网络
- golang之defer
- golang之正则校验
- GoLang之协程
- mysql基础1
- 谷歌二维码生成
- oracle ASM错误Initializing the Oracle ASMLib driver:[FAILED]
- tensorflow中的激活函数
- 文章标题
- Golang之flage
- 每个新手程序员都会犯的5个错误
- 从微软和小米的转型之痛,解读DevOps落地的核心要点
- Spring AbstractRoutingDataSource实现读写分离的Web工程
- 机器学习之KNN算法python实现
- Disruptor 实现无锁队列
- Win10彻底关闭恢复功能,终极省流量设置
- Oracle自定义函数
- Qt之Qwt初探(一)