What's try in try_fold return value? keyword or struct?

Iterator's method try_fold source code:

Last line of try_fold is it's return value.

try { accum }

What's this try in try_fold? Is it a keyword or struct?

It can't, couldn't, be a struct. The try_fold function is generic over the return type, so the caller can choose an arbitrary return type (as long as it implements Try). Therefore, the function body itself can't decide to return a single fixed type.

It is indeed a keyword, the return value of a try block is automatically wrapped in the Ok variant of the R type. That last line is therefore equivalent with R::from_ok(accum). I don't see why the implementation uses a spurious try – it really isn't necessary, and is less obvious, less readable than the equivalent, purely function call based implementation would have been.

1 Like

It's a keyword. See try_blocks - The Rust Unstable Book

1 Like

It's because of the transition to try_trait_v2 (https://github.com/rust-lang/rfcs/pull/3058).

Rather than need to #[cfg] every single try_fold implementation to switch between R::from_ok(a) and R::from_continue(a), they (almost) all use try { a } instead so that the change in the compiler was enough to switch to the new trait structure (Implement the new desugaring from `try_trait_v2` by scottmcm · Pull Request #84767 · rust-lang/rust · GitHub).

It could probably change now, but there's no much value in touching all those places again.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.