Weird Expressions in Rust

https://news.ycombinator.com/rss Hits: 7
Summary

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()); } The the function takes a reference to a Cell<bool>. Inside the function, we use a while loop while !x.get() {x.set(true);} to set the cells contains to true if its contents are false and we return that while loop which has the type (). Next we create a variable i which is a reference to a Cell<bool> and bind a closure that calls the with i as the parameter, we then call that closure and assert that i is true. Zombie jesus fn zombiejesus() { loop { while (return) { if (return) { match (return) { 1 => { if (return) { return } else { return } } _ => { return } }; } else if (return) { return; } } if (return) { break; } } } The expression (return) has the type never, since the never type can coerce into any type we can use it in all these places. In if and while statements it gets coerced into a boolean, in a match statement it gets coerced into anything. let screaming = match(return){ "aahhh" => true, _ => false }; Not sure use std::mem::swap; fn notsure() { let mut _x: isize; let mut _y = (_x = 0) == (_x = 0); let mut _z = (_x = 0) < (_x...

First seen: 2025-06-27 16:27

Last seen: 2025-06-27 22:28