News for hackers. Stuff that matters.
Re:Weird Expressions in Rust by steveklabnik on Friday June 27, 2025 @02:03PM (#44398891)
Respectfully, "it makes no sense to me" isn't an argument. if and break both have types in Rust as well.

> don't even have a return keyword.

This is because they are not procedural languages, it has nothing to do with the type system.

> there is no upside that I can see to this decision in terms of language ergonomics.

There's tremendous upside! That's why lots of languages choose this. For example, there is no need for the ternary in Rust: if can just do that.

> What practical value is it to users to allow "return <expr>" to itself be an expression?

Code like this just works:

        let guess: u32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => return,
        };
That is, if return wasn't an expression, we'd have a type error: the two arms would have incompatible types.
Re:Weird Expressions in Rust by derriz on Friday June 27, 2025 @03:30PM (#44399565)
See my comment above, your example only "just works" if the enclosing function has the appropriate return type (in this case none).

So the syntactic element "return" is not just an expression - unlike other sub-expressions, it involves action at a distance - i.e. it must not just agree with it's context as part of an expression but it must agree with the enclosing fn signature.

Re:Weird Expressions in Rust by steveklabnik on Friday June 27, 2025 @03:34PM (#44399604)
I replied over there, let's keep it to that sub-tree so we both don't have to duplicate comments :)
Re:Weird Expressions in Rust by nine_k on Saturday June 28, 2025 @01:18PM (#44406381)
This makes sense because the `match` returns a union of u32 and `never`.

Assigning values of expressions that are purely `never`, or having values that are purely `never` or `()` as the condition in a conditional operator, should be marked as an error, like unreachable code.