This code is from the cli
Go package: https://github.com/codegangsta/cli
package main
import (
"github.com/codegangsta/cli"
"os"
)
func main() {
app := cli.NewApp()
app.Name = "greet"
app.Usage = "fight the loneliness!"
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "lang, l",
Value: "english",
Usage: "language for the greeting",
},
}
app.Action = func(c *cli.Context) {
name := "someone"
if len(c.Args()) > 0 {
name = c.Args()[0]
}
if c.String("lang") == "spanish" {
println("Hola", name)
} else {
println("Hello", name)
}
}
app.Run(os.Args)
}
I'm a Go beginner and I understand everything, except this part:
if len(c.Args()) > 0 {
name = c.Args()[0]
}
What does that block says? Why is it necessary?
The function Args
returns an object Args
which is a slice of strings (see context.go
):
type Args []string
To get the first element of that slice ([0]
) one has to check beforehand if it's not empty, thus the len
test. If you don't do this and the slice happens to be empty, you get an index out of range
runtime error and your program panics.