2 ms·
> I can't think of any other language that allows return inside an expression ... Rust Er, what? You understand almost everything in Rust is an expression rig
by tialaramex 4y ago
> I can't think of any other language that allows return inside an expression ... Rust
Er, what?
You understand almost everything in Rust is an expression right?
let x = if yeah_nah() { return 5; } else { "X" };
That return is an expression, obviously we mostly care about the expression's side effect which is a change of control flow to leave the function with some sort of integer 5 as the return value (the function signature tells Rust which kind of integer this 5 is) - but the expression "return 5" itself does have a type, it's ! aka Never, an Empty Type because no values of this type can exist - because the side effect will change the control flow before we need a value.
Rust's type inference engine is fine with this because under type arithmetic all the values fit in a single type, the type of "X" - &'static str - there are no values on the left to disrupt that.