Docopt – Golang – How to access repeated arguments?

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

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 (
	&quot;fmt&quot;
	&quot;github.com/docopt/docopt-go&quot;
)

func main() {
	usage := `blah.go

  Usage: 
    blah.go read &lt;file&gt; ...
    blah.go -h | --help | --version`

	arguments, _ := docopt.Parse(usage, nil, true, &quot;blah 1.0&quot;, false)
	x := arguments[&quot;&lt;file&gt;&quot;]
	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 {})

https://github.com/docopt/docopt.go

答案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[&quot;&lt;file&gt;&quot;] 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.

huangapple
  • 本文由 发表于 2014年6月5日 04:30:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/24047008.html
匿名

发表评论

匿名网友

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

确定