Search code examples
godocopt

Docopt - Golang - How to access repeated arguments?


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 {})

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


Solution

  • 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.