I write a quick sort, I was thinking for #105, 'return v;' is identical to 'v'. somehow, it is not.
'return v;' will work, but 'v' will not compile.
Can someone help explain what's the difference among the 2
Can someone help explain what's the difference among the 2
When you pass a value by itself and the end of an expression, you're returning that value to the context above the expression, return is used exclusively to early exit out of function.
return v means to return from the enclosing function immediately with the value in v. v by itself is just the value.
if cond { return v; } means that if cond is true, the function should immediately stop executing and return the value v. if cond { v } just means that if cond is true, the value of the if expression is v.
Thank you!
Only at the end of the function, 'return value;' is the same as 'value'
That's right!
Yes! Execution blocks (code enclosed in {}) are considered expressions, its final value being the last entry in the block without a semicolon. This makes if, match, and other control flow statements ergonomic in Rust. return is to exit early from functions (and not if blocks), usually to report errors.