命令行参数是参数化程序执行的常用方法。 例如,go run hello.go
将go
和hello.go
作为参数应用到go
程序中。
os.args
提供对原始命令行参数的访问。请注意,此切片中的第一个值是程序的路径,os.args [1:]
保存程序的参数。
可以获得正常索引的单个arg
值。
所有的示例代码,都放在
f:\worksp\golang
目录下。安装go编程环境请参考:http://www.h3.com/go/go_environment.html
command-line-arguments.go
的完整代码如下所示 -
package main
import "os"
import "fmt"
func main() {
// `os.args` provides access to raw command-line
// arguments. note that the first value in this slice
// is the path to the program, and `os.args[1:]`
// holds the arguments to the program.
argswithprog := os.args
argswithoutprog := os.args[1:]
// you can get individual args with normal indexing.
arg := os.args[3]
fmt.println(argswithprog)
fmt.println(argswithoutprog)
fmt.println(arg)
}
执行上面代码,将得到以下输出结果 -
f:\worksp\golang>go run command-line-arguments.go 1 2 3 4 5
[c:\users\admini~1\appdata\local\temp\go-build400542858\command-line-arguments\_obj\exe\command-line-arguments.exe 1 2 3 4 5]
[1 2 3 4 5]
3