...

/

Working with Cobra - The Sub-commands

Working with Cobra - The Sub-commands

In this lesson, we’ll define two sub-commands for the calculator application: the `add` and `subtract` commands which look very similar and can serve as a pattern to define additional sub-commands. Then, we'll connect the subcommands to the root command.

The add subcommand

Cobra is all about defining sub-commands. Let’s start with the add subcommand. It will be defined in the cmd/add.go file:

package cmd

import (
	"fmt"
	"gigi/calc/pkg/calc"
	"github.com/spf13/cobra"
	"strconv"
)

var check bool

var addCmd = &cobra.Command{
	Use:   "add",
	Short: "Add two integers",
	Long:  `Add two integers a and b; result = a + b`,
	Args:  cobra.ExactArgs(2),
	Run: func(cmd *cobra.Command, args []string) {
		var a, b int
		var err error
		a, err = strconv.Atoi(args[0])
		if err != nil {
			panic("Arguments to `add` must be integers")
		}
		b, err = strconv.Atoi(args[1])
		if err != nil {
			panic("Arguments to `add` must be integers")
		}

		result := calc.Add(a, b, check)
		fmt.Println(result)
	},
}

Let’s review its ...