gpt4 book ai didi

go - Docopt - Golang - 如何访问重复的参数?

转载 作者:IT王子 更新时间:2023-10-29 02:17:18 28 4
gpt4 key购买 nike

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

最佳答案

根据文档 ( 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)会成功的。

关于go - Docopt - Golang - 如何访问重复的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24047008/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com