frontpage.
newsnewestaskshowjobs

Made with ♥ by @iamnishanth

Open Source @Github

Open in hackernews

Weird Expressions in Rust

https://www.wakunguma.com/blog/rust-weird-expr
74•lukastyrychtr•3h ago

Comments

xyst•2h ago
These “weird expressions” probably get used code golf.
steveklabnik•2h ago
Basically none of them are actually useful, or even do anything, it's mostly a parser stress test.
behnamoh•2h ago
Great, 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. Reading this made me realize Elixir is literally macros all the way down, and it's a Lisp!

ramon156•2h ago
Note 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•1h ago
Kind of like obfuscated C code I suspect.
b0a04gl•2h ago
they 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•56m ago
If 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•53m ago
It 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•53m 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•31m 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.

steveklabnik•24m ago
It is an aspect, but it Rust does not promise your core is secure.

It’s not purely expression based but it is very close to it, there’s only a few kinds of statements, the vast majority of things are expressions.

derriz•30m ago
That sounds superficially reasonable to me and I'm all for regularity in programming language semantics but on thinking about it further, I actually think it's a design flaw.

It makes no more sense to me for "return <expr>" to have a type than it does to make "if <expr>" or "break" or "{" or any other keyword to have a type. These are syntactic elements.

Rust's type system is clearly inspired by Hindley-Milner and most languages using such a type system either don't even have a return keyword.

Even if you disagree with this argument, this design decision has resulted in all these weird/confusing but absolutely useless code examples and there is no upside that I can see to this decision in terms of language ergonomics. What practical value is it to users to allow "return <expr>" to itself be an expression? That you can use such an "expression" as arguments to function calls with hilarious wtf consequences? It's a piece of syntactic sugar.

steveklabnik•18m ago
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.
NobodyNada•13m ago
In practice, it's quite a useful feature, because you can write things like this:

    let day_number = match name {
        "Sunday" => 0,
        "Monday" => 1,
        "Tuesday" => 2,
        "Wednesday" => 3,
        "Thursday" => 4,
        "Friday" => 5,
        "Saturday" => 6,
        _ => return Err("invalid day")
    };
bobbylarrybobby•10m ago
The issue with `return expr` not having a type is that you lose the ability to write something like

let y = match option { Some(x) => x, None => return Err("whoops!"), };

Without a type, the None branch loses the ability to unify with the Some branch. Now you could say that Rust should just only require branches’ types to unify when all of them have a type, but the ! never type accomplishes that goal just fine.

deathanatos•4m ago
We can use match to do pattern matching:

  let name = match color_code {
    0 => "red",
    1 => "blue",
    2 => "green",
    _ => "unknown",
  };
The RHS of the `=>` has to be an expression, since we're assigning it to a variable. Here, you should already see one "useful" side-effect of what you're calling "syntactic elements" (I'd perhaps call them "block statements", which I think is closer to the spirit of what you're saying.) The whole `match … {}` in the example above here is an expression (we assign the evaluation of it to a variable).

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

Now, what if I need to return an error?

  let name = match color_code {
    0 => "red",
    1 => "blue",
    2 => "green",
    _ => return Err("unknown color"),
  };
The expression arms need to be the same type (or what is the type of `name`?). So now the type of the last branch is !. (Which as you hopefully learned from TFA, coerces to any type, here, to &str.)

There's more ways this "block statements are actually expressions" is useful. The need not be a ternary operator / keyword (like C, C++, Python, JS, etc.):

  let x = if cond { a } else { b };
In fact, if you're familiar with JavaScript, there I want this pattern, but it is not to be had:

  const x;  // but x's value will depend on a computation:
  // This is illegal.
  if(foo) {
    x = 3;
  } else {
    x = 4;
  }
  // It's doable, but ugly:
  const x = (function() { if(foo) { return 3; } else { return 4; }})();
  // (Yes, you can do this example with a ternary.
  // Imagine the if branches are a bit more complicated than a ternary,
  // e.g., like 2 statements.)
  
Similarly, loops can return a value, and that's a useful pattern sometimes:

  let x = loop {
    // e.g., find a value in a datastructure. Compute something. Etc.
    if all_done {
      break result;
    }
  };
And blocks:

  let x = {
    // compute x; intermediate variables are properly scoped
    // & cleaned up at block close.
  };
> Even if you disagree with this argument, this design decision has resulted in all these weird/confusing but absolutely useless code examples

I think one can cook up weird code examples in any language.

throwawaymaths•28m ago
its not just that some things you would usually think are control flow are expressions, its also that there are unusual rules around coercing the `noreturn` type.
steveklabnik•2h ago
This 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/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 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•1h ago
What's the joke exactly? English is not my native language.
jerf•1h ago
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•1h ago
Yes, but why is it evil?
Analemma_•49m ago
I think that part is a reference to a Futurama episode where a holodeck malfunction materialized several villains, including "Evil Lincoln".
drfuchs•1h ago
There’s a strong connection between President Lincoln and log cabins. He grew up in a series of log cabins, and this fact was widely known during his campaign.
rendaw•1h ago
What's the joke exactly? English is my native language.
steveklabnik•1h ago
log "lincoln" is a reference to the toy "lincoln logs"
nikolayasdf123•2h ago
this is why I like Go
timeon•1h ago
It does not have stress tests for parser?
nemo1618•1h ago
I 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•56m ago
Makes sense to me, [...]func() is an array of functions, and [...]T{index: value} is uncommon but still perfectly comprehensible
nemo1618•38m ago
Many people aren't aware that you can use key: val declarations in arrays
jenadine•20m ago
That's why I like Rust /s
IshKebab•1h ago
Honestly I'm surprised how not weird these are. Way less WTFy than Javascript, PHP, C or C++.
Thaxll•1h ago
Why assigning a variable to a function that returns nothing is not a compilation error?
steveklabnik•1h ago
Which example are you referencing?
assbuttbuttass•1h ago
There'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
npalli•1h ago
yeah this is good, but now add lifetime annotations to have fun.
steveklabnik•1h ago
Lifetimes are not expressions and therefore can't really be put into odd places.
armchairhacker•42m ago
Related: https://dtolnay.github.io/rust-quiz

Rust programs that give unintuitive outputs or compile errors.

Sniffnoy•7m ago
I 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()?

What is Acid Communism? (2019)

https://medium.com/swlh/what-is-acid-communism-e5c65ecf6188
1•iscream26•4m ago•0 comments

Brazil Supreme Court rules digital platforms to be liable for users' posts

https://apnews.com/article/brazil-supreme-court-social-media-ruling-324b9d79caa9f9e063da8a4993e382e1
2•rogerthis•6m ago•0 comments

Ask HN: What CS or Software Engineering subfields are worth specializing in?

1•pixelworm•6m ago•0 comments

CISA: AMI MegaRAC bug enabling server hijacks exploited in attacks

https://www.bleepingcomputer.com/news/security/cisa-ami-megarac-bug-that-lets-hackers-brick-servers-now-actively-exploited/
2•cws•6m ago•0 comments

Private Equity's Medicaid Problem

https://www.axios.com/pro/health-tech-deals/2025/06/26/private-equity-medicaid-sales
1•cwwc•7m ago•0 comments

H-1B Middlemen Bring Cheap Labor to Citi, Capital One

https://www.bloomberg.com/graphics/2025-h1b-visa-middlemen-cheap-labor-for-us-banks/
3•mfiguiere•7m ago•1 comments

Ranking generative AI companies from most to least evil

https://cwodtke.medium.com/i-love-generative-ai-and-hate-the-companies-building-it-3fb120e512ac
2•anigbrowl•8m ago•0 comments

Code Researcher: Deep Research Agent for Large Systems Code and Commit History

https://arxiv.org/abs/2506.11060
1•PaulHoule•10m ago•0 comments

Leading Without Non-Negotiables Is Just Damage Control

https://scottkosman.com/post/blog/leading-without-non-negotiables/
1•mooreds•13m ago•0 comments

Show HN: A Beautiful Python GUI Framework

https://github.com/mebaadwaheed/winup
3•ebaadesque•18m ago•1 comments

Hosting Website on Phone

https://rohanrd.xyz/posts/hosting-website-on-phone/
2•quaintdev•19m ago•0 comments

Call Center Workers Are Tired of Being Mistaken for AI

https://www.bloomberg.com/news/articles/2025-06-27/as-ai-infiltrates-call-centers-human-workers-are-being-mistaken-for-bots
2•koolhead17•20m ago•1 comments

Any employee can build apps and it's hell for developers

https://writer.com/engineering/agent-development-lifecycle/
4•bproper•21m ago•1 comments

Managed Servers

https://www.hetzner.com/managed-server/
3•dumbledoren•23m ago•1 comments

Show HN: WebDev Club A curated space for web developers to learn, share and grow

https://webdev.club/
1•kkxingh•29m ago•0 comments

Moving My Website from Static Hosting to Caddy (2023)

https://www.apalrd.net/posts/2023/studio_website/
2•indigodaddy•30m ago•0 comments

Play "The Plot of the Phantom" the text adventure that took 40 years to finish

https://scottandrew.com/blog/2025/06/you-can-now-play-plot-of-the-phantom-the-text-adventure-game/
1•SeenNotHeard•30m ago•0 comments

The Alters: unintentionally the realest game about parenting I've ever played

https://www.theguardian.com/games/2025/jun/27/the-alters-unintentionally-the-realest-game-about-parenting-ive-ever-played
1•robaato•31m ago•0 comments

Show HN: Kokonut UI – open-source UI Library

https://kokonutui.com/
1•kokonutt_•31m ago•0 comments

New Study Finds Glass Bottles Leak 50x More Microplastics Than Plastic

https://www.sustainability-times.com/research/glass-is-the-real-threat-new-study-finds-glass-bottles-leak-50x-more-microplastics-than-plastic-alarming-scientists-globally/
1•mgh2•32m ago•1 comments

Coding Agents 101: Some tips for using agents productively

https://devin.ai/agents101
3•waldenyan20•32m ago•1 comments

James Webb Space Telescope Reveals Its First Direct Image of an Exoplanet

https://www.smithsonianmag.com/smart-news/james-webb-space-telescope-reveals-its-first-direct-image-discovery-of-an-exoplanet-180986886/
1•divbzero•37m ago•0 comments

AI CEO

https://replaceyourboss.ai/
2•smartmic•37m ago•0 comments

I built a Figma plugin to create 3D device mockups without leaving Figma

https://www.figma.com/community/plugin/1518871640838086765/mockit-3d-device-mockups
1•lucybuilds•38m ago•0 comments

Data Centers, Temperature, and Power

https://www.backblaze.com/blog/data-centers-temperature-and-power/
2•quectophoton•39m ago•0 comments

KeyConf25

https://keyconf.dev/
1•mooreds•39m ago•0 comments

Another Use for Ice: Creating Secret Codes

https://www.nytimes.com/2025/06/26/science/physics-ice-bubbles-code.html
1•lxm•40m ago•0 comments

Show HN: I made a tool to convert recipes to an easy reading graphical notation

https://gobsmacked.io
2•ekglimmer•41m ago•1 comments

Using a Raspberry Pi as a Thin Client for Proxmox VMs (2022)

https://www.apalrd.net/posts/2022/raspi_spice/
1•indigodaddy•41m ago•0 comments

RTK – query your Rust codebase and make bindings anywhere

https://github.com/reachingforthejack/rtk
1•reaching4jack•41m ago•1 comments