谁能解释一下 Go 中的标志?
flag.Parse()
var omitNewline = flag.Bool("n", false, "don't print final newline")
Run Code Online (Sandbox Code Playgroud)
标志是为命令行程序指定选项的常用方法。
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)
}
Run Code Online (Sandbox Code Playgroud)
运行程序:
go run main.go
Run Code Online (Sandbox Code Playgroud)
通过首先给它不带标志来尝试运行程序。请注意,如果您省略标志,它们会自动采用默认值。
go run command-line-flags.go --env production --port 2000
Run Code Online (Sandbox Code Playgroud)
如果您提供具有指定值的标志,则默认值将被传递的一个覆盖。
有关完整说明,请参阅http://golang.org/pkg/flag/ 。
flag.Bool 的参数是(名称字符串、布尔值、用法字符串)
name 是要查找的参数,value 是默认值,usage 描述了 -help 参数或类似参数的标志用途,并通过 flag.Usage() 显示。
有关更详细的示例,请查看此处
归档时间: |
|
查看次数: |
7400 次 |
最近记录: |