(轉)Golang 讀取作業系統命令列控制檯傳入的引數列表os.Args的多種方式
方法一
/root/code/go/src/contoso.org/book/main.go
package main import ( "fmt" "os" "reflect" "strings" ) func main() { PrintArgs1(os.Args) } //變參函式的定義方式 func PrintArgs1(args ...interface{}) { fmt.Println(args[0].([]string)) fmt.Println(reflect.TypeOf(args[0])) for k, v := range args[0].([]string) { fmt.Println(k, " =", v, reflect.TypeOf(v)) } fmt.Println("========================================") var myStr = (args[0].([]string))[1] //直接點選除錯執行,此行程式碼陣列就越界了 fmt.Println("myStr =", myStr, "myStr Type =", reflect.TypeOf(myStr)) ss := strings.Split(myStr, ",") for k, v := range ss { fmt.Println(k, " =", v, reflect.TypeOf(v)) } }
提示,上面的程式碼寫法沒有任何錯誤,但不能直接點選除錯執行,因為程式執行時必須傳入引數值
[[email protected] ~]# tree $GOPATH/src/contoso.org -L 3 ##檢視專案目錄結構 /root/code/go/src/contoso.org ├── book ├── debug └── main.go
[[email protected] ~]# cd $GOPATH && go install contoso.org/book && cd ~ [[email protected] ~]# book 141,13,105,17,208 [book 141,13,105,17,208] []string 0 = book string 1 = 141,13,105,17,208 string ======================================== myStr = 141,13,105,17,208 myStr Type = string 0 = 141 string 1 = 13 string 2 = 105 string 3 = 17 string 4 = 208 string
方法二
單步除錯之前,設定好Args的初始化值列表,同樣適合上面的範例,直接這樣[[email protected] ~]# book 即可執行book
launch.json:
{ "version": "0.2.0", "configurations": [ { "name": "Launch", "type": "go", "request": "launch", "mode": "debug", "remotePath": "", "port": 2345, "host": "127.0.0.1", "program": "${fileDirname}", "env": {}, "args": ["141","13","105","17","208"], "showLog": true } ] }
方法二的簡寫格式
package main import ( "fmt" "os" "reflect" ) func main() { for _, arg := range os.Args[1:] { fmt.Println("arg =", arg, " arg Type =", reflect.TypeOf(arg)) // 可以把每個字串引數轉換成我們需要的型別 } }
除錯控制檯會輸出以下資訊:
2017/07/02 14:52:02 server.go:73: Using API v1 2017/07/02 14:52:02 debugger.go:97: launching process with args: [/root/code/go/src/contoso.org/book/debug 141 13 105 17 208] API server listening at: 127.0.0.1:2345 2017/07/02 14:52:03 debugger.go:505: continuing arg = 141 arg Type = string arg = 13 arg Type = string arg = 105 arg Type = string arg = 17 arg Type = string arg = 208 arg Type = string
方法三
package main import ( "fmt" "os" "reflect" "strings" ) func main() { fmt.Println(strings.Join(os.Args[1:], " ")) // 傳入的資料量很大,一種簡單且高效的解決方案是使用strings包的Join函式 args := strings.Split(strings.Join(os.Args[1:], " "), " ") for _, arg := range args { fmt.Println("arg =", arg, " arg Type =", reflect.TypeOf(arg)) } }
除錯控制檯列印輸出如下資訊:
2017/07/02 11:21:11 server.go:73: Using API v1 2017/07/02 11:21:11 debugger.go:97: launching process with args: [/root/code/go/src/contoso.org/book/debug 141 13 105 17 208] API server listening at: 127.0.0.1:2345 2017/07/02 11:21:12 debugger.go:505: continuing 141 13 105 17 208 arg = 141 arg Type = string arg = 13 arg Type = string arg = 105 arg Type = string arg = 17 arg Type = string arg = 208 arg Type = string