Is match arm order always defined behaviour?

Given that reddit isn't that authoritative I thought I would ask the question here: Is rust match arm priority guaranteed when there are overlapping matches (which you can get if you have wild cards in a tuple for example)?

Will it always hold that whatever optimisation are applied, that they will have the same effect as if the order was done from top down? (Sorry some times it pays to be paranoid and ask these questions).

( Related reddit post: )

The title is slightly misleading as “guards” aren’t really involved in your question.

The answer is yes, the match arms are evaluated in order of appearance (this is talking about semantics, any optimization that doesn’t change overall program behavior in an observable matter is of course still allowed). With regards to where this is documented, … well, looking into the reference there’s the following description

the […] value is sequentially compared to the patterns in the arms until a match is found. The first arm with a matching pattern is chosen as the branch target of the match, any variables bound by the pattern are assigned to local variables in the arm's block, and control enters the block.

(emphasis mine)


Note that this forum isn't an authoritative source either (but the reference is).

1 Like

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