解析前更改布尔标志的值

Change value of boolean flag before parsing

sandbox/tmp/main.go

package main

import (
    "flag"
    "sandbox/tmp/pac"
)

func main() {
    flag.Set("str_flag", "new_val")
    // flag.Set("bool_flag", true)     // How to set this?
    flag.Parse()
    pac.PrintFlags()
}

sandbox/tmp/pac/pac.go

package pac

import "flag"

var (
    boolFlag = flag.Bool("bool_flag", false, "")
    strFlag  = flag.String("str_flag", "def_val", "")
)

func PrintFlags() {
    println(*boolFlag)
    println(*strFlag)
}

布尔标志的 flag.Set() 的补码是什么?

只需使用您在命令行中提供的字符串表示形式,例如 "true":

flag.Set("bool_flag", "true")

引用自Package doc: Command line flag syntax:

Boolean flags may be:

1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False

因此以下也有效:

flag.Set("bool_flag", "1")
flag.Set("bool_flag", "t")
flag.Set("bool_flag", "T")
flag.Set("bool_flag", "TRUE")
flag.Set("bool_flag", "True")