1

我试图了解如何从 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 {})

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

4

1 回答 1

1

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.

于 2014-06-04T20:46:23.697 回答