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

1

10

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.

Bordure answered 10/8, 2020 at 13:17 Comment(0)
H
13

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.

Hin answered 10/8, 2020 at 13:27 Comment(1)
Excellent, thank you - this is what I had suspected, but I couldn't find anything in the viper or cobra tutorials/instructions/readme that was explicit about it. Hopefully this question will be easier to google...Bordure

© 2022 - 2024 — McMap. All rights reserved.