Should notice two types of flags: Persistent flags & Local flags
add cli:
add num create a command named add, navigate to the project
1 2
G:\go-work\src\mycalc>cobra add add add created at G:\go-work\src\mycalc
rebuild the binary using go install mycalc and run mycalc add.
1
G:\go-work\src\mycalc>go install mycalc
1 2
G:\go-work\bin>mycalc add add called
modify it to add a series of numbers to add numbers, fisrt have to convert the string into int then returan the result.
1 2 3 4
import ( ... "strconv" )
inside the add.go, create a new addInt function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
func addInt(args []string) { var sum int // the first return value is index of args, we can omit it using _ for _, ival := range args { // strconv is the library used fortype conversion, for string // to int conversion Atio method is udes. itemp, err := strconv.Atoi(ival) if err != nil { fmt.Println(err) } sum = sum + itemp } fmt.Printf("Addition of numbers %s is %d, args, sum) }
update RUN func
1 2 3
... addInt(args) ...
rebuild
1 2 3 4
G:\go-work\bin>mycalc add a bc 8 strconv.Atoi: parsing "a": invalid syntax strconv.Atoi: parsing "bc": invalid syntax Addition of numbers [a bc 8] is 8
create a addFloat func in add.go //add.go func addFloat(args []string) { var sum float64 for _, fval := range args { ftemp, err := strconv.ParseFloat(fval,64) if err != nil { fmt.Println(err) } sum = sum + ftemp } fmt.Printf(“sum of floating nums %s is %f”, args,sum) }
1 2 3 4 5 6 7 8 9 10 11 12 13
3. create a addFloat func in addCmd RUN func ``` bash // add.go // addCmd Run: func(cmd *cobra.Command, args []string) { // get the flag value, its default value is false fstatus, _ := cmd.Flags().GetBool("float") if fstatus { addFloat(args) } else { addInt(args) } },
var evenSum int for _, ival := range args { itemp, _ := strconv.Atoi(ival) if itemp%2 == 0 { evenSum = evenSum + itemp } } fmt.Printf("the even addition of %s is %d", args, evenSum) },