Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this if condition always evaluate to false? [GoLang]

I have the following if condition that evaluates the length of string foo – it should always be either 16 or 19 characters. It’ll look something like abcd-efgh-ijkl-mnop or abcdefghijklmnop.

func ValidateFoo(...) error {

    if len(foo) != 16 || len(foo) != 19 {
        return fmt.Errorf("foo should be 16 or 19 characters, %q %d",
            foo,
            len(foo),
        )
    }
...
}

This looks syntactically correct (to me) but when I run tests against this function, they fail with the "foo should be 16 or 19 characters" error.

Strangely, in the output of Errorf(), the len() is always 16 or 19 characters, which obviously makes no sense. eg:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

got error: supplied key is not 16 or 19 characters, key "foo should be 16 or 19 characters" 19

Is my if statement wrong?

Edit:

My if statement is wrong. Should use logical AND not OR https://stackoverflow.com/a/72889607/8859720

>Solution :

The if statement is always true. For it to be false, len(foo) must be both 16 and 19. Use &&, not ||.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading