英文:
What is the most concise way of passing named arguments to a Golang tool and to use them?
问题
目标: 将命名参数传递给一个 Golang 工具,并将传递的参数用作变量
尝试
编译以下示例:
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
根据这个答案,将以下代码片段添加到示例中:
s := strings.Split(arg, "=")
variable, value := s[0], s[1]
fmt.Println(variable, value)
构建并传递参数后,输出如下:
[./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
问题
尽管目标已经实现,但我想知道这是否是在 Golang 中传递命名参数并使用它们的最简洁方式。
英文:
Aim: to pass named arguments to a Golang tool and to use the passed arguments as variables
Attempt
Compiling the following example:
> 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)
> }
build it and pass arguments, e.g.: ./args -a=1 -b=2 -c=3 -d=4 -e=5 -f=6
, results in:
[./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
Based on this answer, the following snippet was added to the example:
s := strings.Split(arg, "=")
variable, value := s[0], s[1]
fmt.Println(variable, value)
and after building it and passing arguments the output is as follows:
[./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
Question
Although the aim has been accomplished I wonder whether this is the most concise way to pass named arguments and to use them in Golang.
答案1
得分: 6
> 包标志
>
> import "flag"
>
> 包flag实现了命令行标志解析。
尝试使用flag
和其他类似的包。
英文:
> Package flag
>
> import "flag"
>
> Package flag implements command-line flag parsing.
Try the flag
and other similar packages.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论