Go语言提供了对命令行解析的内置支持,并具有可用于定义标志的函数,这些标志可与命令行程序一起使用,flag
包。该软件包提供了flag.Bool()函数,该函数用于定义具有指定名称,默认值和用法字符串的布尔标志。
用法:
func Bool(name string, value bool, usage string) *bool
参数:此函数接受上述和以下描述的三个参数:
- name:它是一个字符串,指定用于标志的名称。
- value:它是一个布尔值,它指定标志使用的默认值。
- usage:它是一个字符串,指定要为该标志显示的用法或帮助消息。
返回值:它返回布尔变量的地址,该变量存储定义的标志的值。
以下示例程序旨在说明flag.Bool()函数:
范例1:
// Golang program to illustrate
// the flag.Bool() Function
package main
import (
"flag"
"fmt"
)
func main() {
// Define a bool flag
boolArgPtr:= flag.Bool("arg1", false, "This is a bool argument")
// Parse command line
// into the defined flags
flag.Parse()
fmt.Println("Bool Arg:", *boolArgPtr)
}
输出:
- 指定标志值
$ go run ex1.go -arg1=true Bool Arg:true
- 未指定标志值(默认值)
$ go run ex1.go Bool Arg:false
范例2:
// Golang program to illustrate
// the flag.Bool() Function
package main
import (
"flag"
"fmt"
)
func main() {
// Define multiple bool arguments
plainArgPtr:= flag.Bool("plaintext", false, "Enable plaintext")
jsonArgPtr:= flag.Bool("json", false, "Enable JSON")
csvArgPtr:= flag.Bool("csv", false, "Enable CSV")
// Parse command line into the defined flags
flag.Parse()
fmt.Println("Enable plaintext:", *plainArgPtr)
fmt.Println("Enable JSON:", *jsonArgPtr)
fmt.Println("Enable CSV:", *csvArgPtr)
}
输出
- 指定一些标志值
$ go run ex2.go -plaintext=true -csv=true Enable plaintext:true Enable JSON:false Enable CSV:true
- 没有指定任何标志值(默认值)
$ go run ex2.go Enable plaintext:false Enable JSON:false Enable CSV:false
相关用法
- Golang math.Lgamma()用法及代码示例
- Golang math.Float64bits()用法及代码示例
- Golang atomic.AddInt64()用法及代码示例
- Golang atomic.StoreInt64()用法及代码示例
- Golang reflect.FieldByIndex()用法及代码示例
- Golang string.Contains用法及代码示例
- Golang bits.Sub()用法及代码示例
- Golang io.PipeWriter.CloseWithError()用法及代码示例
- Golang time.Round()用法及代码示例
- Golang reflect.AppendSlice()用法及代码示例
- Golang reflect.ChanOf()用法及代码示例
- Golang time.Sleep()用法及代码示例
- Golang time.Time.Year()用法及代码示例
- Golang reflect.DeepEqual()用法及代码示例
- Golang reflect.Indirect()用法及代码示例
- Golang reflect.CanAddr()用法及代码示例
- Golang reflect.CanInterface()用法及代码示例
- Golang reflect.CanSet()用法及代码示例
- Golang reflect.Cap()用法及代码示例
- Golang strings.ContainsRune()用法及代码示例
注:本文由纯净天空筛选整理自sayantanm19大神的英文原创作品 flag.Bool() Function in Golang With Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。