以下是 c.Args() > 0 的用途:

huangapple go评论76阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年2月17日 18:42:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/28560094.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定