package main
import (
"flag"
"fmt"
"os"
)
func main() {
//取得命令列參數(變數為指標)
varAA := flag.String("aa", "ABC", "字串參數")
varBB := flag.Int("bb", 123, "整數參數")
varCC := flag.Bool("cc", false, "布林值參數")
//取得命令列參數(將現有變數,設定為接收為參數)
var varDD string
flag.StringVar(&varDD, "dd", "DEF", "字串參數")
flag.Parse()
fmt.Println("aa:", *varAA)
fmt.Println("bb:", *varBB)
fmt.Println("cc:", *varCC)
fmt.Println("dd:", varDD)
fmt.Println("不在規定內,其他形式的參數:", flag.Args())
fmt.Println("另一個方式,使用os.Args取得參數陣列 os.Args :", os.Args)
fmt.Println("另一個方式,使用os.Args取得參數陣列 os.Args[0]:", os.Args[0])
if len(os.Args) > 1 {
fmt.Println("另一個方式,使用os.Args取得參數陣列 os.Args[1]:", os.Args[1])
}
}[結果]
D:\Go>go build cmd_arg.go
D:\Go>cmd_arg -h
Usage of cmd_arg:
-aa string
字串參數 (default "ABC")
-bb int
整數參數 (default 123)
-cc
布林值參數
-dd string
字串參數 (default "DEF")
D:\Go>cmd_arg
aa: ABC
bb: 123
cc: false
dd: DEF
不在規定內,其他形式的參數: []
另一個方式,使用os.Args取得參數陣列 os.Args : [cmd_arg]
另一個方式,使用os.Args取得參數陣列 os.Args[0]: cmd_arg
D:\Go>cmd_arg -bb=99 -dd=XYZ ww xx dfs
aa: ABC
bb: 99
cc: false
dd: XYZ
不在規定內,其他形式的參數: [ww xx dfs]
另一個方式,使用os.Args取得參數陣列 os.Args : [cmd_arg -bb=99 -dd=XYZ ww xx dfs]
另一個方式,使用os.Args取得參數陣列 os.Args[0]: cmd_arg
另一個方式,使用os.Args取得參數陣列 os.Args[1]: -bb=99
D:\Go>cmd_arg -bb=99 -dd=XYZ ww xx dfs
aa: ABC
bb: 99
cc: false
dd: XYZ
不在規定內,其他形式的參數: [ww xx dfs]
另一個方式,使用os.Args取得參數陣列 os.Args : [cmd_arg -bb=99 -dd=XYZ ww xx dfs]
另一個方式,使用os.Args取得參數陣列 os.Args[0]: cmd_arg
另一個方式,使用os.Args取得參數陣列 os.Args[1]: -bb=99
D:\Go>cmd_arg -bb 99 -dd XYZ ww xx dfs
aa: ABC
bb: 99
cc: false
dd: XYZ
不在規定內,其他形式的參數: [ww xx dfs]
另一個方式,使用os.Args取得參數陣列 os.Args : [cmd_arg -bb 99 -dd XYZ ww xx dfs]
另一個方式,使用os.Args取得參數陣列 os.Args[0]: cmd_arg
另一個方式,使用os.Args取得參數陣列 os.Args[1]: -bb參考:
- https://gobyexample.com/command-line-arguments
Go by Example: Command-Line Arguments - https://gobyexample.com/command-line-flags
Go by Example: Command-Line Flags - https://gobyexample.com/command-line-subcommands
Go by Example: Command-Line Subcommands
沒有留言:
張貼留言