Add an implementation for the Default trait for std::ops::ControlFlow

I think it would make a lot of sense for ControlFlow<T, B> to implement Default when T: Default, with the value returned being Continue(T::default()). This is a small addition that can be useful in certain contexts. Choosing Continue as the default variant seems obvious to me, but if anyone feels different perhaps this could be confusing and should be disregarded. I would like to hear your opinion.

Isn't ControlFlow used in situations where it's ambiguous whether the "normal"/"successful" behavior is breaking or continuing? This seems to me like it would have a significant risk of being the wrong default; and returning Continue in particular could cause an unintended infinite loop. It also would not be good for readability, because understanding the resulting control flow requires knowing the answer to the question "what does Default do?".

10 Likes

IMHO it's much more obvious that "Default for Result should be Ok" than "Default for ControlFlow should be Continue". And yet even Result doesn't implement it.

Why "more obvious"?: I see ControlFlow as "like Result but without the semantic extra assumptions Result comes with", in other words ControlFlow should be more symmetrical in treating it's variants than Result is, and basically the only asymmetry should be in the behavior for the ? operator (and other uses of the Try trait).

Presumably a major reason why Result doesn't offer a Default based on Ok is that Option implements Default returning None!

9 Likes

This is absolutely 100% the intent of the type, yup.

It replaces code that was extremely confusing because it was using Err for "success" because having ? short-circuit that was helpful. This is also why while Result has map and map_err but ControlFlow has map_break and map_continue: Neither variant is "preferred" over the other.

8 Likes

How fitting that I had also written a note about precisely the naming choice for these map methods but then didn't include it for brevity. :safety_critical_ferris_1:

4 Likes