问题描述
如何在 Golang 中将列表作为标志变量传递?例如,在 Bash 中,您可以将列表作为 getopts 传递给脚本。类似的东西:
./myScript.sh -n list_of_names.txt //some file with about 50 names
然后循环遍历列表:
#!/bin/bash
while getopts "n:h:" options; do
case "${options}" in
"n") NAME=${OPTARG};;
"h") PRINT_USAGE;;
esac
done
for i in $NAME; do
//Todo
我听说过“flag”包,但我不知道如何实现
PS 我完全是 Go 的新手
解决方法
在你的例子中,你真的只有一个必需的参数,所以你真的没有 需要解析任何东西。您可以只检查切片长度:
package main
import "os"
func main() {
if len(os.Args) != 2 {
println("myScript <file>")
os.Exit(1)
}
name := os.Args[1]
println(name)
}