Weird Expressions in Rust
Purpose and nature of “weird expressions”
- Many commenters see these snippets as code-golf / parser stress tests, not patterns you’d ever accept in a PR.
- Even experienced Rust developers report needing time to parse them and would reject such code as unreadable.
- The blog’s focus is mostly on putting expressions in unusual positions and exploiting implicit
()and!types, not on realistic code.
Expression-based design and the ! (“never”) type
- Rust treats almost everything as an expression: blocks,
if,match, loops, macros, and evenreturn,break,continue. return <expr>and similar constructs have type!, an uninhabited “never returns” type that coerces to any other type.- This enables ergonomic patterns like
match/ifarms that either produce a value or early-return/abort without type errors (e.g.None => return Err(...)). - Several examples and explanations clarify that
!is useful in generic code and in typing non-returning functions or error types (Result<T, !>).
Debate: regularity vs. confusion
- One side argues that giving
returna type and making control-flow constructs expressions increases uniformity and reduces special cases, especially for generics and macros. - The opposing view calls this a design flaw:
returndepends on the enclosing function’s signature and has “action at a distance,” so it’s not a normal expression; the upside is small while it enables puzzling, useless constructs. - Some suggest the compiler should warn when
!or()appear in conditions or other obviously nonsensical positions.
Readability, security, and safety boundaries
- Concern: a language that allows highly unintuitive constructs might hinder security reviews; incomprehensible code can hide bugs or malicious logic.
- Counterpoint: truly “weird Rust” is highly artificial; normal idiomatic Rust remains readable and still benefits from strong typing, lints, and memory safety.
- It’s noted that you can still have UB in “safe Rust” via unsound tricks that effectively disable parts of the type/borrow checker, and that malicious logic doesn’t require
unsafe. - Consensus advice: if code looks strange or non-idiomatic, don’t merge it without fully understanding it.
Comparisons and side topics
- Several comments compare Rust’s weirdness favorably to JS/PHP/C/C++; others show “weird” but still comprehensible Go examples.
- There are clarifications about
unionbeing a contextual keyword for compatibility,i += 1returning()in one example, and confusion around macros likeassert!. - New learners are reassured that none of this is required knowledge; it’s mostly trivia and edge-case exploration.