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

How to accept input in a single line using cobra library in Go

我正在使用 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