gpt4 book ai didi

go - Go中的Flags解释

转载 作者:IT王子 更新时间:2023-10-29 00:41:07 25 4
gpt4 key购买 nike

谁能解释一下 Go 中的标志?

flag.Parse()
var omitNewline = flag.Bool("n", false, "don't print final newline")

最佳答案

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

先给它一个不带标志的程序来尝试运行程序。请注意,如果您省略标志,它们会自动采用默认值。

go run command-line-flags.go --env production --port 2000

如果您提供具有指定值的标志,则默认值将被传递的值覆盖。

关于go - Go中的Flags解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1726891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com