英文:
What's the use of the following c.Args() > 0
问题
这段代码是来自cli
Go包: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)
}
我是一个Go初学者,我理解了除了这部分之外的所有内容:
if len(c.Args()) > 0 {
name = c.Args()[0]
}
这段代码的作用是什么?为什么它是必要的?
英文:
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?
答案1
得分: 4
函数Args
返回一个名为Args
的对象,它是一个字符串切片(参见context.go
):
type Args []string
要获取该切片的第一个元素([0]
),必须事先检查它是否为空,因此需要进行len
测试。如果不这样做,而切片恰好为空,就会出现index out of range
的运行时错误,导致程序崩溃。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论