gpt4 book ai didi

go - 如何在 Cobra golang 中使用子命令?

转载 作者:数据小太阳 更新时间:2023-10-29 03:47:42 26 4
gpt4 key购买 nike

抱歉,我找不到使用示例的方法

./client echo --times 10 "coucou" 
./client --times 10 "coucou" echo

无法使用它...抱歉我的错误。

最好的问候,尼古拉斯

    func main() {
var echoTimes int

var cmdEcho = &cobra.Command{
Use: "echo [string to echo]",
Short: "Echo anything to the screen",
Long: `echo is for echoing anything back.
Echo works a lot like print, except it has a child command.
`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Print: " + strings.Join(args, " "))
},
}

var cmdTimes = &cobra.Command{
Use: "times [# times] [string to echo]",
Short: "Echo anything to the screen more times",
Long: `echo things multiple times back to the user by providing
a count and a string.`,
Run: func(cmd *cobra.Command, args []string) {
for i:=0; i < echoTimes; i++ {
fmt.Println("Echo: " + strings.Join(args, " "))
}
},
}

cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")
var rootCmd = &cobra.Command{Use: "app"}
rootCmd.AddCommand(cmdEcho)
cmdEcho.AddCommand(cmdTimes)
rootCmd.Execute()
}

最佳答案

如果 times 是一个命令,您不应该在它前面加上 '--'。

您可以在 cobra_test.go 中看到的示例显示 times 用法如下:

echo times -j 99 one two
echo times -s again -c test here

关于go - 如何在 Cobra golang 中使用子命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27493482/

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