package main import ( "fmt" "github.com/spf13/cobra" ) func main() { var rootCmd = &cobra.Command{ Use: "hello", Short: "Prints a greeting message", Long: `This command prints a greeting message to the console.`, Run: func(cmd *cobra.Command, args []string) { fmt.Println("Hello, world!") }, } rootCmd.Execute() }
package main import ( "fmt" "strconv" "github.com/spf13/cobra" ) func main() { var rootCmd = &cobra.Command{ Use: "sum [number1] [number2]", Short: "Calculates the sum of two numbers", Long: `This command calculates the sum of two numbers passed as arguments.`, Args: cobra.ExactArgs(2), Run: func(cmd *cobra.Command, args []string) { number1, _ := strconv.Atoi(args[0]) number2, _ := strconv.Atoi(args[1]) result := number1 + number2 fmt.Println("Sum of", number1, "and", number2, "is", result) }, } rootCmd.Execute() }In this example, we define a root command `sum` that accepts two arguments `number1` and `number2`. The `Args` field is used to specify the exact number of arguments expected by the command. The `strconv.Atoi` function is used to convert the arguments from strings to integers before performing the addition operation. The result is then printed to the console.