Rust has a very powerful type system, but as a result it has some quirks, some would say cursed expressions. There’s a test file, weird-expr.rs , in the rust repository that tests for some of these and makes sure there consistent between updates. So I wanted to go over each of these and explain how it’s valid rust.
Note that these are not bugs, but rather extreme cases of rust features like loops, expressions, coercion and so on.
Strange
fn strange () -> bool { let _x : bool = return true ;}
The expression return true has the type ! . The never type can coerce into any other type, so we can assign it to a boolean.
Funny
fn funny (){ fn f (_x : ()){} f ( return ); }
The function f has a single parameter of () type, we can again pass return because ! will be coerced into () .
What
use std :: cell :: Cell ; fn what (){ fn the (x : & Cell < bool >){ return while ! x . get () {x . set ( true );}; } let i = & Cell :: new ( false ); let dont = { || the (i)}; dont (); assert! (i . get ()); }
... continue reading