Tricky subcommand outputs

Report a typo

Below you will see a Go program that contains two subcommands reverse and repeat:

package main

import (
    "flag"
    "fmt"
    "log"
    "os"
)

func main() {
    reverse := flag.NewFlagSet("reverse", flag.ExitOnError)
    reverseName := reverse.String("name", "User", "Enter the name to reverse")

    repeat := flag.NewFlagSet("repeat", flag.ExitOnError)
    repeatName := repeat.String("name", "User", "Enter the name to be repeated")
    repeatCount := repeat.Int("count", 1, "Enter the number of repetitions")

    switch os.Args[1] {
    case "reverse":
        reverse.Parse(os.Args[2:])
        runes := []rune(*reverseName)
        for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
            runes[i], runes[j] = runes[j], runes[i]
        }
        fmt.Printf("%s", string(runes))
    case "repeat":
        repeat.Parse(os.Args[2:])
        for i := 0; i < *repeatCount; i++ {
            fmt.Printf("%s\n", *repeatName)
        }
    default:
        log.Fatal("Error! Expected 'repeat' or 'reverse' subcommands")
    }
}

Select all the ways to execute the program using subcommands, without outputting any default values from their flags!

Select one or more options from the list
___

Create a free account to access the full topic