如何访问传递给Go程序的命令行参数?

如何在Go中访问命令行参数? 它们不作为parameter passing给main

一个完整的程序,可能是通过链接多个包创build的,必须有一个名为main的包,带有一个函数

 func main() { ... } 

定义。 函数main.main()不带任何参数,并且不返回任何值。

您可以使用os.Argsvariables访问命令行参数。 例如,

 package main import ( "fmt" "os" ) func main() { fmt.Println(len(os.Args), os.Args) } 

您也可以使用标志包 ,它实现了命令行标志parsing。

命令行参数可以在os.Args中find。 在大多数情况下,包标志是更好的,因为它为你parsing参数。

彼得的答案正是你所需要的,如果你只是想要一个参数列表。

但是,如果您正在寻找与UNIX上相似的function,那么您可以使用docopt的 执行 。 你可以在这里尝试。

docopt将返回JSON,然后可以处理您的心脏的内容。

国旗是一个很好的包装。

 // [_Command-line flags_](http://en.wikipedia.org/wiki/Command-line_interface#Command-line_option) // are a common way to specify options for command-line // programs. For example, in `wc -l` the `-l` is a // command-line flag. package main // Go provides a `flag` package supporting basic // command-line flag parsing. We'll use this package to // implement our example command-line program. import "flag" import "fmt" func main() { // Basic flag declarations are available for string, // integer, and boolean options. Here we declare a // string flag `word` with a default value `"foo"` // and a short description. This `flag.String` function // returns a string pointer (not a string value); // we'll see how to use this pointer below. wordPtr := flag.String("word", "foo", "a string") // This declares `numb` and `fork` flags, using a // similar approach to the `word` flag. numbPtr := flag.Int("numb", 42, "an int") boolPtr := flag.Bool("fork", false, "a bool") // It's also possible to declare an option that uses an // existing var declared elsewhere in the program. // Note that we need to pass in a pointer to the flag // declaration function. var svar string flag.StringVar(&svar, "svar", "bar", "a string var") // Once all flags are declared, call `flag.Parse()` // to execute the command-line parsing. flag.Parse() // Here we'll just dump out the parsed options and // any trailing positional arguments. Note that we // need to dereference the pointers with eg `*wordPtr` // to get the actual option values. fmt.Println("word:", *wordPtr) fmt.Println("numb:", *numbPtr) fmt.Println("fork:", *boolPtr) fmt.Println("svar:", svar) fmt.Println("tail:", flag.Args()) }