1

I have written a program to calculate basic arithmetic functions using interfaces in Go language.

I want to do the same using COBRA commands. Here is some Go code using interfaces.

I have also implemented the arithmetic functions using cobra commands without the interfaces.

this is addition using cobra commands without using the concept of interfaces, I want to implement the same using cobra commands.

package cmd

    import (
        "fmt"

        "github.com/spf13/cobra"

        "os"

        "strconv"
    )

    func addCmd() *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 := addCmd()
        RootCmd.AddCommand(cmd)

    }

Can someone help me out with the interfaces and the cobra commands.

Matthew Strawbridge
  • 19,940
  • 10
  • 72
  • 93
Manu
  • 77
  • 2
  • 11
  • Please show exactly where you are stuck and what have you tried. http://stackoverflow.com/help/mcve – Sachin Nambiar Nalavattanon Feb 06 '17 at 09:19
  • I want use the concept of interfaces in cobra to implement a calculator.I want to implement a method called operations for addition, subtraction, multiplication, division.I have done it using the go language but I don't know how to do the same using cobra commands, Should I do it in a separate command ..? – Manu Feb 08 '17 at 03:43
  • I don't know what you mean by the "concept of interfaces in Cobra." Are you trying to make all of the commands interfaces? If so, why? – Aor Dec 05 '17 at 15:01
  • Also, the way you add your command is not good practice. Instead of having a static function which creates and returns the addition command, you should define the command outside of a function and bind it to RootCmd in init() directly. `var addition = &cobra.Command{...}` ... `func init() {RootCmd.AddCommand(addition)}` – Aor Dec 05 '17 at 15:11

0 Answers0