HUGO

What is the neatest way to do "if x or y or z.."?

I was thinking of doing something like {{ if or (or x y) (or a b) }}

Is there a better way?

Thank you :slight_smile:

The or and and functions accept a variable number of arguments.

{{ or 0 0 0 }} --> 0
{{ or 1 0 0 }} --> 1
{{ or 0 2 0 }} --> 2
{{ or 0 0 3 }} --> 3
{{ or 1 2 3 }} --> 1
{{ or 1 2 0 }} --> 1
{{ or 1 0 3 }} --> 1
{{ or 0 2 3 }} --> 2

See https://pkg.go.dev/text/template#hdr-Functions

or
Returns the boolean OR of its arguments by returning the
first non-empty argument or the last argument, that is,
“or x y” behaves as “if x then x else y”. All the
arguments are evaluated.

Note the last sentence. This will no longer be true once go 1.18 is released.

1 Like

Thank you! So shall I keep my current way of doing it if it’ll be changed soon?

So shall I keep my current way of doing it if it’ll be changed soon?

No. What will change is the “All the arguments are evaluated” behavior. This is a good, nuanced, non-breaking change.

Take this example:

“You can have a cookie if you can prove that (a) your heart is beating, OR (b) you can run 20 kilometers.”

With go 1.17 and earlier, you would have to demonstrate both, even though the condition is satisfied with the first argument (your heart is beating).

With go 1.18 and later, you can have the cookie immediately. Your heart is beating, so there’s no need to evaluate anything else. This is known as “short-circuiting” or “short circuit evaluation.”

4 Likes

I see, that’s useful. Thank you very much for educating me on this! :smiley:

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.