go 语言文件操作:从命令行读取参数 | go 技术论坛-江南app体育官方入口
1 使用os包读取命令行参数
os包有一个全局变量args,是[]string类型,第一个元素是程序名
示例代码
func main() {
for i, v := range os.args {
fmt.printf("这是第%d个参数:%s\n", i, v)
}
}
运行结果
nothin:~/gopractice/flags$ go build -o flag
nothin:~/gopractice/flags$ ./flag p1 p2 p3
这是第0个参数:./flag
这是第1个参数:p1
这是第2个参数:p2
这是第3个参数:p3
2 使用flag包
flag包就比os.args更加灵活,不过其也有一些限制,比如说官方不推荐在init函数中调用flag.parse,这样会使得不同包之间的flag出现问题
示例代码
func main() {
str := flag.string("s", "hello world", "test string")
num := flag.int("n", 0, "test number")
bol := flag.bool("b", false, "test bool")
//在使用flag包定义的参数之前,一定要先运行parse
flag.parse()
fmt.println("string paramter:", *str)
fmt.println("number parameter:", *num)
fmt.println("bool parameter", *bol)
}
运行结果
nothin:~/gopractice/flags$ ./flag2 -s="hello world" -n=123 -b=true
string paramter: hello world
number parameter: 123
bool parameter true
#这里加一个-d,因为程序内部没有定义d,所以程序会出错并抛出预先写好的usage
nothin:~/gopractice/flags$ ./flag2 -s="hello world" -n=123 -b=true -d
flag provided but not defined: -d
usage of ./flag2:
-b test bool
-n int
test number
-s string
test string (default "hello world")
参考: