17 ms·
Weird Expressions in Rust
- xyst 1y agoThese “weird expressions” probably get used code golf.
- steveklabnik 1y agoBasically none of them are actually useful, or even do anything, it's mostly a parser stress test.
- behnamoh 1y agoGreat, now this stuff gets fed into LLM trainings and we'll see them in the next-gen model outputs. Seriously though, I love "abusing" programming languages in unexpected ways. My favorite so far is: https://evuez.net/posts/cursed-elixir.html https://evuez.net/posts/cursed-elixir.html. Reading this made me realize Elixir is literally macros all the way down, and it's a Lisp!
- ramon156 1y agoNote that for Rust devs these are also weird syntaxes. I feel like some people assume that an experienced dev can read these, but it takes a while to get what's going on.
- ChuckMcM 1y agoKind of like obfuscated C code I suspect.
- dathinab 1y agoyes, but less risky (and less power full) because you often very fast can conclude that "whatever it does it's safe, sound and doesn't affect unrelated code"
- caim 1y agoAnd how would you conclude that "fast"? You can have UB in "safe rust". https://github.com/Speykious/cve-rs https://github.com/Speykious/cve-rs You can even disable the Type check, trait check and borrow check in "safe rust" And all of this is unsound. https://users.rust-lang.org/t/i-finally-found-the-cheat-code-for-disabling-the-type-checker-s/123624 https://users.rust-lang.org/t/i-finally-found-the-cheat-code...
- jenadine 1y agoOr you can have malicious code that is not unsafe. Does it mix sensible data with something that is being sent? Does it always accept "return break union" as a valid password? Things like that.
- dathinab 1y agoyes, but that is a different kind of unreadable code then in the blog the blog focuses mainly on putting expresions into unusual positions and how some things have an implicite () type and some an implicite ! type etc. either way if you see strange code you probably shouldn't copy/merge it without having a very good understanding of what it does
- 01HNNWZ0MV43FF 1y agoYeah. I've been doing Rust for a few years and when I look at these I just see "Failed PR review, unreadable to humans"
- b0a04gl 1y agothey exist because whole language built to treat expressions as firstclass citizens : blocks, ifs, matches, even macros as expressions that return values. so once you internalize that, all these weirdo one liners are artifacts. just artifact of a system where expressions compose infinitely. the syntax tree runs deeper than most people's habbits allow. you hit that depth and brain says this is wrong but compiler's allowing.
- gmueckl 1y agoIf a language that claims to be security focused is easily able to express constructs that human minds find barely comprehensible, or worse, then this is itself arguably a security issue: it's impossible to check the correctness of logic that is incomprehensible.
- PaulHoule 1y agoIt is a critique of macros. 500 lines of Common Lisp replaces 50,000 lines of C++ but those 500 lines make no sense at all the first time you see them.
- steveklabnik 1y ago> If a language that claims to be security focused Rust does not claim to be particularly security-focused, only memory safe. Also, this means that you'd consider any expression-based language to be inherently a security problem.
- gmueckl 1y ago"Memory safety" is an aspect of computer security. And security is the first listed value in rust's mission statement. Rust is not written as a pure expression based language. And as we all know very well from the experience with C and JS, any unexpected and weird looking code has the potential to hide great harm. Allowing programmers to stray too much from expected idioms is dangerous.
- 1y ago
- steveklabnik 1y agoThis post is missing my favorite one! fn evil_lincoln() { let _evil = println!("lincoln"); } What's weird about this? To understand what evil_lincoln is doing, you have to understand very old Rust. Here's the commit that introduced it: https://github.com/rust-lang/rust/commit/664b0ad3fcead4fe4d22c05065a82a338770c429 https://github.com/rust-lang/rust/commit/664b0ad3fcead4fe4d2... fn evil_lincoln() { let evil <- log "lincoln"; } log was a keyword to print stuff to the screen. Hence the joke, https://en.wikipedia.org/wiki/Lincoln_Logs https://en.wikipedia.org/wiki/Lincoln_Logs Now that log is the println! macro, the joke is lost. It doesn't say explicitly why this is "weird", but given some other comments in the file, // FIXME: Doesn't compile //let _x = log true == (ret 0); I am assuming that using the return value of log was buggy, and so this tested that you could save it in a variable. I don't remember the exact semantics of log, but if it's like println!, it returns (), which is useless, so binding it to a variable is something you'd never write in real code, so it's "weird" in that sense.
- ibotty 1y agoWhat's the joke exactly? English is not my native language.
- jerf 1y agohttps://www.basicfun.com/lincoln-logs/ https://www.basicfun.com/lincoln-logs/ This would be something the Boomer generation grew up with, and I think maybe the previous generation too. They're still around but they've certainly faded; they used to be Lego-level popular kids toys back then. They are named after President Lincoln, but only as a marketing tactic to use some of his reputation, there's no real connection. I would imagine even some native English speakers are learning something with this post. I haven't seen them in a while.
- ranguna 1y agoYes, but why is it evil?
- 1y ago
- nikolayasdf123 1y agothis is why I like Go
- timeon 1y agoIt does not have stress tests for parser?
- nemo1618 1y agoI wonder, what's the "weirdest" expression in Go? Here's one: type Foo struct{} func (Foo) Bar() { println("weird...") } func main() { ([...]func(){^^len(` `): (&Foo{}).Bar})[cap(append([]any(nil),1,2,3))]() }
- assbuttbuttass 1y agoMakes sense to me, [...]func() is an array of functions, and [...]T{index: value} is uncommon but still perfectly comprehensible
- nikolayasdf123 1y agothis the worst? not too bad. fairly comprehensible.
- yencabulator 1y agoI have a personal fondness for silly variations of type __ *[]*__
- techbrovanguard 1y agothis is not the gotcha you think it is, you just dropped your gluestick
- IshKebab 1y agoHonestly I'm surprised how not weird these are. Way less WTFy than Javascript, PHP, C or C++.
- dathinab 1y agoyes but to be fair the blog is focused on unusual aspects of everything being an expression you still can create some more confusing things by idk. overloading some operators (but luckily not `=` and similar crazy C++ things) adding recursive macros and maybe combining it with lifetime variance and coercion edge cases, maybe sprinkle in some arcane `#[]` annotations and people with be very confused, more so then in the article
- IshKebab 1y agoYeah... I'm just saying I haven't seen anything close to these things: https://github.com/denysdovhan/wtfjs https://github.com/denysdovhan/wtfjs https://github.com/satwikkansal/wtfpython https://github.com/satwikkansal/wtfpython
- Thaxll 1y agoWhy assigning a variable to a function that returns nothing is not a compilation error?
- steveklabnik 1y agoWhich example are you referencing?
- assbuttbuttass 1y agoThere's no such thing as a "function that returns nothing" in Rust. Unit, written as (), is a first class value and can be assigned to a variable, although there's not much point
- tialaramex 1y agoDo you mean a function which returns "nothing" in the sense that it does return but it has no particular value to return, like Vec::clear which gets rid of the values but preserves the capacity of the container ? In Rust the return type of this function is the unit type, the empty tuple (). So, the variable has this type, there's no problem with this in Rust, even though some lesser languages can't handle the idea of a type this small. Or did you mean a function which never returns, like std::process::exit ? In Rust this function's return type is ! the Never type, an empty type that you ordinarily can't name in stable Rust. Because this type is empty, a variable of this type will evaporate, the compiler knows that we can't bring values into existence if there are no values of that type, the code paths in which this variable exists will never be executed, so no need to emit machine code. In a language with generic programming like Rust this isn't an error, it's actually a convenience. We can write generic error handling code, and then for cases where there will never be an error our error handling code doesn't even compile, it evaporates entirely, yet for cases which can have actual errors, the error handling code is emitted.
- dathinab 1y agoassuming you mean returning () (the empty tuple/void type) because it doesn't compose well with generics, macros, proc-macros etc. e.g. if you have this dump way to wrap clone: `fn foo<T: Clone>(v: T) -> (T, T) { let new = v.clone(); (v, new) }` it would implicitly not work with T = (), because then `v.clone()` would be a "function which returns nothing". In isolation this might seem fine but if you compose abstractions you sooner or later run into an edge case where it isn't fine. And this becomes even more a problem when macros/proc-macros are involved. It also makes changing code easier, lets say you have something like `let x = foo(); dbg!(x);` and you change the return type it will keep compiling as long as the type implements `Debug`, even if you change the type to `()` (i.e. return nothing). And again for normal code that is a minor nit pick, but for macros, proc macros, generic code of sufficient complexity sooner or later you run into edge cases where it really matters that it's allowed. Not often but often enough. Lastly and most importantly assigning `()` to a variable hurts no one, you won't see any such code in normal PRs. So it it doesn't hurt anyone but can be quite use full in edge cases. Lastly linters (mainly clippy) do warn or error for some of this nonsensical things, depending on the lint-set you enabled.
- npalli 1y agoyeah this is good, but now add lifetime annotations to have fun.
- steveklabnik 1y agoLifetimes are not expressions and therefore can't really be put into odd places.
- armchairhacker 1y agoRelated: https://dtolnay.github.io/rust-quiz https://dtolnay.github.io/rust-quiz Rust programs that give unintuitive outputs or compile errors.
- Sniffnoy 1y agoI don't understand the one with dont(). Why does i.get() end up false at the end? Shouldn't it be true after having been set by dont()?
- LegionMammal978 1y agoThe final line "assert!(i.get());" asserts that i.get() is true in the end. The ! character here belongs to the assert! macro, not a boolean negation. (This unfortunately gets a bit weird-looking when you want to write sensible stuff like "if !matches!(x, Some(5..=10)) { ... }".)
- Sniffnoy 1y agoOops, I see, thanks!
- arjvik 1y agoI figured out how return-as-a-value made sense only upon realizing that in the following code, fn funny(){ fn f(_x: ()){} f(return); } f() is never called because funny() returns before it gets called. The reason you want return to be coercible to any type is so that you can write something like let x: i32 = if y { 4 } else { return; // type ! coerced into i32 } And you pick the return value of ! because return never actually produces a value that is propagated on at runtime, it immediately exits the function. (Note this all works even with returning a value)
- kzrdude 1y agoMany of them are on the same theme - the theme is `return -> !`. Here's my favourite on that theme, which I was missing from the list: return return return return return return return return return 1
- pluto_modadic 1y agoI've absolutely seen some /cursed/ rust one liners. if you extend it to the most cursed ~6 lines of code, you really can obfuscate what you're doing in a way that's fiendishly hard to debug.
- munificent 1y agoDoes anyone know why `union` isn't a reserved word in Rust? Most contextual keywords in other languages come from either: 1. Features that were added after the language was in wide use and can't add keywords without breaking existing code. 2. Features where the word is particularly useful elsewhere, so would be painful to reserve (like `get` and `set` in Dart). But neither of those seem to apply to Rust. As far as I know, it's always had ML-style unions, and "union" doesn't seem to be a particularly useful identifier otherwise. Why isn't `union` fully reserved?
- steveklabnik 1y agoIt's simply that Rust has higher standards for breaking changes than "probably not in wide use." In other words, that someone could have had `let union =`... somewhere was a reason to make it contextual. https://rust-lang.github.io/rfcs/1444-union.html#contextual-keyword https://rust-lang.github.io/rfcs/1444-union.html#contextual-...
- munificent 1y agoOoooooh, I see my confusion now. My brain switched off and I got enums and unions confused. I was like, wait, hasn't Rust had them since day one? I was thinking of `enum`, not `union`. My bad.
- steveklabnik 1y agoAhhh yeah, no worries!
- pitaj 1y agoIt's a common operation on sets, so would make `HashSet::union` [1] and friends less obvious, for no real benefit. [1] https://doc.rust-lang.org/stable/std/collections/struct.HashSet.html#method.union https://doc.rust-lang.org/stable/std/collections/struct.Hash...
- JoeOfTexas 1y agoBruh, I started learning Rust yesterday. Why do you do this to me. Now I don't know anything I studied.
- steveklabnik 1y agoYou don't need to know any of this. It's just a parsing stress test, with meaningless programs. It's fun trivia.
- xg15 1y agoRust noob here. That '!' type seemed weird in the first few examples but starts to make sense later on. It's essentially a "pseudo type" for everything that is syntactically an expression, but will never return anything, because evaluating it causes the entire statement to be canceled. Is that correct?
- Analemma_ 1y agoYes. If you look at steveklabnik's example with the match statement elsewhere in the comments, it makes sense that '!' is the "never" or "unreachable" type, not because the return expression isn't run, but because its value will never be assigned to a variable, since it causes an unconditional exit from the function.
- NobodyNada 1y agoYes, exactly -- it's called the Never type. It's also useful in more places than return expressions -- for example, you can make a function return ! to indicate that it's a non-returning function, which is useful for expressing, say, an error handler that must crash the program; or a main loop that must never return. It also can help the compiler generate more compact code when a function is known to not return. There's currently work in progress to allow you to specify ! as a type everywhere, not just as function returns. This is useful where some generic code expects a function to return a Result with an implementation-specified error type, since an infallible implementation can specify ! as the error type. Then, the type checker can allow the programmer to unwrap a Result<T, !> without checking for errors, and the optimizer can remove the error-checking branches from generic code: https://doc.rust-lang.org/std/primitive.never.html https://doc.rust-lang.org/std/primitive.never.html This has taken a very long time to implement, because of some very subtle implications on type inference that made it difficult to stabilize without breaking compatibility -- but the 2024 edition finally figured out a way to make it possible.
- int_19h 1y agoNot necessarily the entire statement, just some outer expression. Which might make more sense when you remember that the only statements in Rust are various declarations (`let`, `type`, `fn` etc) and macro invocations. Everything else is an "expression statement", including blocks and loops. Thus you can do stuff like: // Compute the first Fibbonaci number >10 let n = { let mut x1 = 0; let mut x2 = 1; loop { let x = x1 + x2; if x > 10 { break x } x1 = x2; x2 = x; } }; Note that `break` never leaves the let-statement here - it just terminates the loop expression and forces it to yield a value (`break` without arguments yields (), and ditto for loops without break). You can also break out of regular blocks if they are labelled and you use the labelled form of break: let x = 'label: { ... break 'label 42 ... } This all can very easily lead to convoluted code if not used sparingly, but sometimes a mutating loop with mutable data encapsulated within and a break to yield it once the computation is complete is genuinely the most straightforward way to write something.
- lacker 1y agoI think there's a mistake in the explanation for "bathroom_stall". When describing the guard in this expression: if (i+=1) != (i+=1) The post says, "The if statement is always going to be false because the right expression will always be one more than the left." But it's a not-equals. The if statement is always going to be false because in Rust "i += 1" doesn't return an integer value, it returns a (). So comparing any two += statements, they are always equal. Since the guard is a != comparison, the if statement is always false.
- keybored 1y agoOnce I tried how many `{{{...}}}` I needed to make javac crash. It wasn’t that many.
- sureglymop 1y agoWith yesterdays release let chains got released. Really needed feature but can sometimes look pretty cursed: https://blog.rust-lang.org/2025/06/26/Rust-1.88.0/#let-chains https://blog.rust-lang.org/2025/06/26/Rust-1.88.0/#let-chain...
- bensons1 1y agoI am sort of amused, a memory safe language deploys this sort of juggling
- nfrmatk 1y agoThere's a fun RustConf talk on this topic from a few years ago. https://youtu.be/tNVDjMxCz-c https://youtu.be/tNVDjMxCz-c
- creative1122 1y ago[dead]
- matt_kantor 1y agoMany moons ago[1] I wrote this, which seems appropriate to share here: fn main() { println!(r#"{:X?}{}"#, __=(|&__@_:&'_ _,|->_{[(|(..,_,__,_,):(_,_,((),),)|__..__)(__)]})({&(!(({"\"__'\\\\\ \'";(||{('\"');()})();}>=*&())|(|__|__||__|__)((()<())&(()>()))),&[..=..],({0__.%-// 0.;(|_:[();0],|{})([[],[],][0]);},),)}),_={(|_0_:[_;0],_:&[()]|{;_0_})({{[0;0]}},&[[ ]][(0..)][{..}][0],);""},); } [1]: https://www.reddit.com/r/rust/comments/8p013f/comment/e094qjo/?context=2 https://www.reddit.com/r/rust/comments/8p013f/comment/e094qj...
- benreesman 1y agoI'm actually working on a project I'm quite serious about but jokingly refer to as "Ergonomic Rust", which would make all of it a weird expression in Rust. It's a C++23 library suite and lint set that eliminates: - UB in all but the most contrived cases (I think I can get it to zero with a modest clang patch set) - bounds errors (see below) - bans all naked pointers and most references of any kind (NVRO and elision are mandated since 17, and on modern hardware like `znver5` you're usually pessimizing with e.g. `const foo_t& foo`) - and has no `usafe` keyword to fall back on, that's enforced at the conceptual module level by having things declare they are unsafe in their entirety via `extern "C"` This stuff is really unlocked by C++23: ``` template<typename T> concept SafeIndexable = requires(T& t, const T& ct, size_t idx) { { t.at(idx) } -> std::same_as<typename T::reference>; { ct.at(idx) } -> std::same_as<typename T::const_reference>; // Banned: t[idx] }; // Wrapper that forces .at() usage template<SafeIndexable Container> class Safe { Container c; public: // Forward everything except operator[] template<typename... Args> Safe(Args&&... args) : c(std::forward<Args>(args)...) {} // Evil genius move: operator[] calls .at() auto operator[](size_t idx) -> decltype(auto) { return c.at(idx); // Throws on bounds violation! } auto operator[](size_t idx) const -> decltype(auto) { return c.at(idx); } // Forward other operations auto begin() { return c.begin(); } auto end() { return c.end(); } // ... etc }; // Usage: Safe<std::vector<int>> vec{1, 2, 3}; vec[10]; // Throws std::out_of_range instead of UB! ```