go - 如何在 Go 中使用 cobra 库在一行中接受输入

标签 go input go-cobra

我正在使用 cobra 用 go 语言编写代码,目前我给出的输入是:

 Calc add 
           Enter the Number of inputs
           2
           Enter the Numbers
           2
           4
 Output: Sum is : 6

在本文中,那些熟悉 cobra 的人,Calc 是我的项目,add 是我使用的命令,我希望输入为 Calc add N2 2 4(在一行中)并且应该显示输出,其中 N 是标识输入数量的变量,2 4 是要添加的数字。

添加命令的代码:

package cmd

import (
    "fmt"

    "github.com/spf13/cobra"
)

// addCmd represents the add command
var addCmd = &cobra.Command{
    Use:   "add",
    Short: "Addition value of given Numbers",

    Run: func(cmd *cobra.Command, args []string) {
        length := 0
    fmt.Println("Enter the number of inputs")
    fmt.Scanln(&length)
    fmt.Println("Enter the inputs")
    numbers := make([]int, length)
    for i := 0; i < length; i++ {
        fmt.Scanln(&numbers[i])
    }
      fmt.Println(numbers)

      sum:=0

for _, numbers := range numbers {

sum += numbers

}

fmt.Println("The Sum :",sum)


 },
}

func init() {
    RootCmd.AddCommand(addCmd)


}

P

最佳答案

这将实现您的目的。将您的号码放入标志 --input 中。给出其他数字作为参数添加。

func NewCmd() *cobra.Command {
    var input int
    c := &cobra.Command{
        Use:   "add",
        Short: "Addition value of given Numbers",

        Run: func(cmd *cobra.Command, args []string) {
            if len(args) != input {
                fmt.Println(fmt.Sprintf("You need to provide %v number to sum up", input))
                os.Exit(1)
            }
            numbers := make([]int, input)
            for i := 0; i < input; i++ {
                num, _ := strconv.Atoi(args[i])
                numbers[i] = num
            }
            sum := 0
            for _, numbers := range numbers {
                sum += numbers
            }
            fmt.Println("The Sum :", sum)
        },
    }
    c.Flags().IntVar(&input, "input", 0, "Number of input")
    return c
}

func init() {
    cmd := NewCmd()
    RootCmd.AddCommand(cmd)
}

输入:

Calc add --input=3 6 3 6

输出: 总和:15

关于go - 如何在 Go 中使用 cobra 库在一行中接受输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41756540/

相关文章:

http - 如何在GET请求golang中发送JSON正文?

sql - 使用 Go 和数据库/sql 扫描 nil 浮点值时出错

Golang 导入结构并共享所有应用程序

javascript - javascript是否禁止将输入类型从密码更改为密码?

input - hadoop可以从多个目录和文件中获取输入吗

javascript - http.FileServer 响应错误 mime "Content-Type"

r - 错误: path for html_dependency not provided R Markdown selectInput

go - Cobra 子命令默认调用帮助

go - Cobra 更改帮助模板中的用法行

json - 如何提供 JSON 数组作为 cobra cli 的参数