Go 语言文件操作:从命令行读取参数 1 个改进

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")

参考:studygolang.com/pkgdoc

本文为 Wiki 文章,邀您参与纠错、纰漏和优化
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!