将命名参数传递给Golang工具并使用它们的最简洁方法是什么?

huangapple go评论77阅读模式
英文:

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

Package flag

> 包标志
>
> import "flag"
>
> 包flag实现了命令行标志解析。

尝试使用flag和其他类似的包。

英文:

> Package flag
>
> import "flag"
>
> Package flag implements command-line flag parsing.

Try the flag and other similar packages.

huangapple
  • 本文由 发表于 2015年11月15日 23:50:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/33721620.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定