Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to get the value of the BoolVar to be false in this case #613

Closed
researchlab opened this issue Jan 15, 2018 · 2 comments
Closed

How to get the value of the BoolVar to be false in this case #613

researchlab opened this issue Jan 15, 2018 · 2 comments

Comments

@researchlab
Copy link

researchlab commented Jan 15, 2018

I hope to get the false value, but always get true from toggle and tog boolean varaibles.
$ ./demo --toggle false --tog false
I hope get the following answer:
tog= false err=
toggle= false

But I got the following one:
tog= true err=
toggle= true

here is the demo code:

package cmd
import (
	"fmt"
	"os"
	"github.com/spf13/cobra"
)

var (
	toggle bool
)

var RootCmd = &cobra.Command{
	Use: "demo",
	Run: func(cmd *cobra.Command, args []string) {
		tog, err := cmd.Flags().GetBool("tog")
		fmt.Println("tog=", tog, " err=", err)
		fmt.Println("toggle=", toggle)
	},
}

func init() {
	RootCmd.PersistentFlags().BoolVarP(&toggle, "toggle", "t", false, "toggle bool")
	RootCmd.Flags().BoolP("tog", "o", false, "tog bool")
}

func Execute() {
	if err := RootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
}

is there any error in above codes ?

@eparis
Copy link
Collaborator

eparis commented Jan 15, 2018

I made some minor changes to your program and hopefully this explains things. Basically, booleans can only take arguments via --bool=[true|false] or for short names -b=[true|false]. You cannot use --bool [true|false] nor can you use the shorthand -b[true|false]. For flags with NoOptDefVal pflag is unable to tell if the argument was meant for the flag or if it was meant for the generic args []string

$ ./test
args: []string{}
tog: false
toggle: false

$ ./test --tog
args: []string{}
tog: true
toggle: false

$ ./test --tog --toggle
args: []string{}
tog: true
toggle: true

$ ./test --tog false --toggle
args: []string{"false"}
tog: true
toggle: true

$ ./test --tog false --toggle false
args: []string{"false", "false"}
tog: true
toggle: true

$ ./test --tog=false --toggle=false
args: []string{}
tog: false
toggle: false

@researchlab
Copy link
Author

I got it, Thank you very much. @eparis

BlackHole1 added a commit to BlackHole1/ovm-js that referenced this issue Jan 24, 2024
BlackHole1 added a commit to oomol-lab/ovm-js that referenced this issue Jan 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants