I'm maintaining some code written using Go (golang), Viper and Cobra.
On one line, it has:
rootCmd.PersistentFlags().String("cfg", "", "A description")
And then on the following line it has
rootCmd.PersistentFlags().StringP("output", "o", ".", "Another description")
What is the difference between String
and StringP
in this context?
Looking at example usages in various tutorials, there seem to be P
and non-P
versions of various methods, such as StringVarP
and StringVar
.
What is the difference between these versions? What is the significance of the P
?
Is there a way I can tell whether a given method has a P
or non-P
counterpart?
Search engines tend to take me to cobra or viper tutorial pages, which make use of these methods without explaining the P
or non-P
counterpart.
I found some material on pflags
which suggested it might be to do with whether the parameter has a short (one-letter) form. Could this be it?
Post-edit note: Having received answers to this question, it seems spf13/pflag
is indeed used under the hood by the above mentioned golang frameworks. However, it's not immediately clear that one should go looking through the pflags documentation when using cobra or viper.
As this is a Q&A site, I've reverted an edit that removed many of the keywords I would have entered when looking for this answer, as I feel others looking for the same information will be better served that way.
The P
suffix denotes a function that accepts a single letter flag name in addition to the full name, as documented in the usage section of the pflag docs:
The pflag package also defines some new functions that are not in flag, that give one-letter shorthands for flags. You can use these by appending 'P' to the name of any function that defines a flag.
To answer your individual questions:
P
functions take an extra parameter: the single letter name. This short flag can be used with a single -
.P
counterpart: all of them, as can be seen in the pflag reference
As for why this is documented in pflag and not viper or cobra, this is because both viper and cobra use the pflag library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With