Читать книгу Practical Go - Amit Saha - Страница 44

Accept Name via a Positional Argument

Оглавление

First, update the config struct to have a name field of type string as follows:

type config struct { numTimes int name string }

Then the greetUser() function will be updated to the following:

func greetUser(c config, w io.Writer) { msg := fmt.Sprintf("Nice to meet you %s\n", c.name) for i := 0; i < c.numTimes; i++ { fmt.Fprintf(w, msg) } }

Next, we update the custom error value as follows:

var errInvalidPosArgSpecified = errors.New("More than one positional argument specified")

We update the parseArgs() function now to look for a positional argument and, if one is found, set the name attribute of the config object appropriately:

if fs.NArg()> 1 { return c, errInvalidPosArgSpecified } if fs.NArg() == 1 { c.name = fs.Arg(0) }

The runCmd() function is updated so that it only asks the user to input the name interactively if not specified, or if an empty string was specified:

func runCmd(rd io.Reader, w io.Writer, c config) error { var err error if len(c.name) == 0 { c.name, err = getName(rd, w) if err != nil { return err } } greetUser(c, w) return nil }

The complete program with all of the preceding changes is shown in Listing 1.7.

Practical Go

Подняться наверх