有谁能解释一下Go中的标志吗?
flag.Parse()
var omitNewline = flag.Bool("n", false, "don't print final newline")发布于 2009-11-13 11:46:17
有关完整描述,请参阅http://golang.org/pkg/flag/。
flag.Bool的参数是(名称字符串、值布尔值、用法字符串)
name是要查找的参数,value是默认值,usage为-help参数或类似参数描述标志的用途,并使用flag.Usage()显示。
有关更详细的示例,请查看here
发布于 2014-06-13 15:28:05
flags是为命令行程序指定选项的常用方法。
package main
import (
"flag"
"fmt"
)
var (
env *string
port *int
)
// Basic flag declarations are available for string, integer, and boolean options.
func init() {
env = flag.String("env", "development", "a string")
port = flag.Int("port", 3000, "an int")
}
func main() {
// Once all flags are declared, call flag.Parse() to execute the command-line parsing.
flag.Parse()
// Here we’ll just dump out the parsed options and any trailing positional
// arguments. Note that we need to dereference the points with e.g. *evn to
// get the actual option values.
fmt.Println("env:", *env)
fmt.Println("port:", *port)
}运行程序:
go run main.go先在不带标志的情况下运行run程序。请注意,如果省略了标志,它们会自动采用默认值。
go run command-line-flags.go --env production --port 2000如果您提供了一个具有指定值的标志,则默认设置将被传递的标志覆盖。
发布于 2009-11-13 11:13:20
flag用于解析命令行参数。如果您将"-n“作为命令行参数传递,则omitNewLine将被设置为true。这一点在教程中有更深入的解释:
在导入标志包之后,第12行创建了一个全局变量来保存
的-n标志的值。变量omitNewline的类型为* bool,指向bool的指针。
https://stackoverflow.com/questions/1726891
复制相似问题