030*_*030 4 arguments go command-line-arguments
目标:将命名参数传递给 Golang 工具并将传递的参数用作变量
试图
编译以下示例:
Run Code Online (Sandbox Code Playgroud)package main import ( "fmt" "os" ) func main() { argsWithProg := os.Args argsWithoutProg := os.Args[1:] arg := os.Args[3] fmt.Println(argsWithProg) fmt.Println(argsWithoutProg) fmt.Println(arg) }
构建它并传递参数,例如:./args -a=1 -b=2 -c=3 -d=4 -e=5 -f=6,结果是:
[./args -a=1 -b=2 -c=3 -d=4 -e=5 -f=6]
[-a=1 -b=2 -c=3 -d=4 -e=5 -f=6]
-c=3
Run Code Online (Sandbox Code Playgroud)
基于此答案,以下代码片段已添加到示例中:
s := strings.Split(arg, "=")
variable, value := s[0], s[1]
fmt.Println(variable, value)
Run Code Online (Sandbox Code Playgroud)
构建并传递参数后,输出如下:
[./args -a=1 -b=2 -c=3 -d=4 -e=5 -f=6]
[-a=1 -b=2 -c=3 -d=4 -e=5 -f=6]
-c=3
-c 3
Run Code Online (Sandbox Code Playgroud)
问题
尽管目标已经实现,但我想知道这是否是传递命名参数并在 Golang 中使用它们的最简洁的方法。