命令行參數(shù)是參數(shù)化程序執(zhí)行的常用方法。 例如,go run hello.go將go和hello.go作為參數(shù)應(yīng)用到go程序中。
os.Args提供對(duì)原始命令行參數(shù)的訪問(wèn)。請(qǐng)注意,此切片中的第一個(gè)值是程序的路徑,os.Args [1:]保存程序的參數(shù)。
可以獲得正常索引的單個(gè)arg值。
所有的示例代碼,都放在
F:\worksp\golang目錄下。安裝Go編程環(huán)境請(qǐng)參考:http://www.yiibai.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)
}
執(zhí)行上面代碼,將得到以下輸出結(jié)果 -
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