Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between StringVar vs StringVarP or String vs StringP when using Go (golang), cobra and viper?

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.

like image 739
M_M Avatar asked Aug 10 '20 13:08

M_M


1 Answers

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:

  • what's the difference: the P functions take an extra parameter: the single letter name. This short flag can be used with a single -.
  • which methods have a 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.

like image 128
Marc Avatar answered Nov 09 '22 00:11

Marc