英文:
How to reference go-flag IsSet, functional code example needed
问题
对于你的问题,你可以使用IsSet
函数来判断选项是通过标志还是默认值进行设置的。在你的代码中,你可以通过opts.Port
来访问选项的值,然后使用IsSet
函数来检查该选项是否被设置过。如果返回true
,则表示选项是通过标志设置的;如果返回false
,则表示选项是通过默认值设置的。
以下是修改后的代码示例:
package main
import (
"fmt"
"github.com/jessevdk/go-flags"
)
func main() {
var opts struct {
Port int `short:"p" long:"Port" description:"IP port" default:"1111"`
}
_, err := flags.Parse(&opts)
if err != nil {
fmt.Println(err)
return
}
if flags.IsSet(opts.Port) {
fmt.Println("Option was set via flag")
} else {
fmt.Println("Option was set via default value")
}
}
希望对你有帮助!如果还有其他问题,请随时提问。
英文:
New to Go, and having a basic conceptual problem (I think)...
Trying to use github.com/jessevdk/go-flags and have it mostly working. --help and whatnot are working fine, flags are being passed, etc.
I need to understand if a option was set via a flag or via go-flags parser using the provided default value. It appears go-flags has an "IsSet" function, but I'm clueless how to reference it. Presume:
var opts struct {
Port int `short:"p" long:"Port" description:"IP port" default:"1111"
}
_, err := flags.Parse(&opts)
I can reference the value via "opts.Port", but how can I find out if the option was set via a flag or default? Many thanks in advance!
答案1
得分: 3
弄清楚了:
parser := flags.NewParser(&opts, flags.Default)
o := parser.FindOptionByLongName("Port")
if o.IsSet() {}
问题是,如果标志在命令行上使用了或者通过默认设置了,IsSet()
就会返回 true。
所以解决了引用 IsSet()
的表面问题,但仍在寻找一种能够告诉我发生了哪种情况的方法,因为我希望标志的默认值显示在 --help 中。
英文:
Figured this out:
parser := flags.NewParser(&opts, flags.Default)
o := parser.FindOptionByLongName("Port)
if o.IsSet() {}
Problme is that IsSet()
is true if the flag was used on the command line OR if it was set via the default.
So solved the surface problem of referencing IsSet()
but still hunting for an ability to tell which occured, since I want the flag defaults to show in --help.
答案2
得分: 0
这里也有一个新手。IsSetDefault()
也是可用的。(也许是因为你提出问题并回答后添加的。)
英文:
Go newbie here as well. IsSetDefault()
is also available. (Perhaps, it was added since you asked and answered your question.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论