Reputation: 3585
Very new to Go and the library to learn command line arguments I am using is urfave/cli. This time I would like to iterate over all the flags created and see what is the default value for all of the flags created irrespective of the fact that it has been set or not on the command line.
To elaborate more on the question. Say, I have 5 mixed flags(int & string),
f1 - int,
f2 - string,
f3 - string,
f4 - int,
f5 - int
with the respective default values in the command line. For int the default value is 0 and the for string, it is "".
During the invocation of the program, I pass :
go program -f1 10 -f2 "abc"
Now, Later in my go code, I would like to iterate over all the flags created and check their values.
So, I am writing this kind of code:
for _, element := range app.VisibleFlags() {
printf("%s\n", element.GetValue())
}
& this tell me that method GetValue does not exists whereas if I go to the official documentation, it seems it is there. Here.
./main.go:353:32: element.GetValue undefined (type cli.Flag has no field or method GetValue)
What did I miss and what option do I have to iterate over all the flags and print their defaults.
Upvotes: 1
Views: 313
Reputation: 7440
VisibleFlags returns an interface Flag (link). On that interface the method GetValue is not defined.
The underlying implementations seem to have GetValue
but possibly not all of them and you can for example access the method by casting to the specific type.
You can also define your own interface with GetValue method and try to cast to that. If that is successful the underlying type has the method and you can use it.
for _, element := range app.VisibleFlags() {
valuerElem, ok := element.(interface {
GetValue() string
})
if !ok {
fmt.Printf("type %T doesn't have a GetValue method\n", element)
continue
}
fmt.Printf("%s\n", valuerElem.GetValue())
}
Upvotes: 0