3 ms·
So does this mean if I call `f(return)`, it will return from the calling context without ever calling the function `f`?
by skohan 5y ago
So does this mean if I call `f(return)`, it will return from the calling context without ever calling the function `f`?
- ben0x539 5y agoyes, it's roughly comparable to { let x = return; f(x) } where the call to f is clearly happening after an unconditional return. A slightly more practical example might be something like f(if blah() { 42 } else { return }) which works out to, roughly, { let x; if blah() { x = 42; } else { return; } f(x) } To get realistic, if you write f(g()?) you basically get f(match g() { Ok(x) => x, Err(e) => return Err(e), }) which is how rust does error propagation without exceptions and without constantly repeating a golang-style mantra.
- chrismorgan 5y agoBuilding on the more practical example, this sort of conditional early return is extremely common in Rust, because expression-orientation makes it very pleasant to use. Here’s a sketch of some of the sorts of ways it can happen in state machine: loop { // … state = match state { A => B, // normal B => break, // exits the loop C => { …; continue; }, // does something and then returns to the start of the loop, skipping setting the state and anything else D => return, // exits the whole thing E => f()?, // if f() returns an Err or None or similar, it’ll return early }; // … }