Skip to content

Instantly share code, notes, and snippets.

@alok87
Created November 19, 2016 03:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alok87/818bab558d0badb821bb0260809acdd8 to your computer and use it in GitHub Desktop.
Save alok87/818bab558d0badb821bb0260809acdd8 to your computer and use it in GitHub Desktop.
spf13/cobra Providing conditional default values
## Question
Suppose i have a command cmd
```
cmd --opt1=['public'|'private'] --opt2=[true|false]
```
How do i define `--opt2` defaut value to `false` if `--opt1` is `public`
and `--opt2` default value to `true` if `--opt1` is `private` ?
## Answer
Do below in your Run()
````
o1v := flagSet.GetString("opt1")
o2changed := flagSet.Changed("opt2")
if o2changed {
return
}
if o1v == "public" {
flagSet.Set("opt2", "false")
} else if o1v == "private" {
flagSet.Set("opt2", "true")
}
````
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment