英文:
Docopt - Golang - How to access repeated arguments?
问题
我正在尝试理解如何从docopt.Parse()的输出中访问多个输入参数。
示例:
package main
import (
"fmt"
"github.com/docopt/docopt-go"
)
func main() {
usage := `blah.go
Usage:
blah.go read <file> ...
blah.go -h | --help | --version`
arguments, _ := docopt.Parse(usage, nil, true, "blah 1.0", false)
x := arguments["<file>"]
fmt.Println(x)
fmt.Println(x)
}
命令行:
$ go run blah.go read file1 file2
[file1 file2]
[file1 file2]
我想只打印出file1或file2。
当我尝试添加:
fmt.Println(x[0])
我得到以下错误:
$ go run blah.go read file1 file2
# command-line-arguments
./blah.go:19: invalid operation: x[0] (index of type interface {})
你可以尝试将x转换为切片类型,然后再访问索引。例如:
files := x.([]string)
fmt.Println(files[0])
这样应该可以打印出file1。
英文:
I'm trying to understand how to access multiple input arguments from docopt.Parse() output.
Example:
package main
import (
"fmt"
"github.com/docopt/docopt-go"
)
func main() {
usage := `blah.go
Usage:
blah.go read <file> ...
blah.go -h | --help | --version`
arguments, _ := docopt.Parse(usage, nil, true, "blah 1.0", false)
x := arguments["<file>"]
fmt.Println(x)
fmt.Println(x)
}
Command Line:
$ go run blah.go read file1 file2
[file1 file2]
[file1 file2]
I'd like to print out only file1 or file2.
When I try adding:
fmt.Println(x[0])
I get the following error:
$ go run blah.go read file1 file2
# command-line-arguments
./blah.go:19: invalid operation: x[0] (index of type interface {})
答案1
得分: 1
根据文档(https://godoc.org/github.com/docopt/docopt.go#Parse),返回类型是map[string]interface{}
,这意味着arguments["<file>"]
会给你一个类型为interface{}
的变量。这意味着你需要进行某种类型转换才能使用它(http://golang.org/doc/effective_go.html#interface_conversions)。可能x.([]string)
会起到作用。
英文:
According to the documentation (https://godoc.org/github.com/docopt/docopt.go#Parse) the return type is map[string]interface{}
which means arguments["<file>"]
gives you a variable of type interface{}
. This means you'll need a type conversion of some sort to use it (http://golang.org/doc/effective_go.html#interface_conversions). Probably x.([]string)
will do the trick.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论