r/rust • • Aug 03 '26

🧠 educational Branchless Rust: Making a Filter 4x Faster by Removing an if

Thumbnail greyblake.com
573 Upvotes

r/rust • • 16d ago

🧠 educational Why building a Rust LSP is hard

Thumbnail rust-glancer.github.io
404 Upvotes

r/rust • • Jan 11 '26

🧠 educational TIL you can use dbg! to print variable names automatically in Rust

689 Upvotes

I've been writing println!("x = {:?}", x) like a caveman for months. Turns out dbg!(x) does this automatically and shows you the file and line number too.

The output looks like: [src/main.rs:42] x = 5

It also returns the value so you can stick it in the middle of expressions: let y = dbg!(x * 2) + 3; and it'll print what x * 2 evaluates to without breaking your code.

I only found this because I fat-fingered a println and my IDE autocompleted to dbg! instead. Been using it everywhere now for debugging and it's way faster than typing out the variable name twice.

Probably common knowledge but figured I'd share in case anyone else is still doing the println dance.

r/rust • • Apr 29 '26

🧠 educational Bugs Rust Won't Catch

Thumbnail corrode.dev
390 Upvotes

r/rust • • Aug 22 '24

🧠 educational I sped up serde_json strings by 20%

Thumbnail purplesyringa.moe
1.1k Upvotes

r/rust • • 12d ago

🧠 educational Rust enums are gold for compilers

170 Upvotes

Hello,

for the last couple of years, I've been working on machine learning library in rust, learning tons about compilers along the. The single most used feature of the language be far were enums.

There is a couple of reasons for that.

1. Rust enums carry value

Duh, we all know that. Yes, of course. But other languages don't. C++ doesn't (yes, there is std::variant and no, "they are not the same" :). Having values enables me to do this very simple variant, straight impossible or awkward in other languages:
Binary { x: OpId, y: OpId }
In other languages, this would've been tag, a union type or even completely unrepresentible. For example in tinygrad (python), it's a tag plus untyped src list, which can contain anything, depending on the tag.
Also notice that OpId(u32) is a newtype! Another beautiful rust feature that gives us zero cost type safety. It's like a pointer, but only with the pointer arithmetic that I want, all access checked and no fighting borrowck.

2. Rust enums can be nested

This is another beautiful feature, which allows this:
Binary { x: OpId, y: OpId, bop: BOp } enum BOp { Add, Sub, Mul } A world of combinatorial options making decomposition and recomposition very natural.

3. Rust enums are TINY

The above nested code has two enums. That means two tags, each with 4 byte size, right? Right? Not in rust :) In rust, it's single 4 byte tag (as the OpId is 4 byte aligned). The tag combines BOp and the Op enum with the Binary variant, so the whole enum is just 12 bytes. I have more complex variants,

4. The allmighty match

So you can do this:

match op {
  Binary { x, y, bop } if bop == BOp::Add => todo!(),
  _ => {}
}

or this:

match (uop, bop) { (UOp::Exp, BOp::Mul) => todo!(), }

And so on. This kind of flexibility in an imperative language, is tons of fun, makes writing compiler passes not only easy, but most importantly, high performance.

And so for example thanks to this my ML lib can search and run cost function over thousands of kernel variants per second and per core (as rust makes multithreading fun too!).

I know you probably know about these features, but sometimes it helps to refresh our memory how nice of a language we have.

What are your favorite rust features?

What features would you like to see added?

I hope you enjoy writing rust just as I did.

zk4x

P. S. link to the repo: github.com/zk4x/zyx

r/rust • • Jan 04 '25

🧠 educational Please stop overly abstracting example code!

787 Upvotes

I see this far too much, and it makes examples near worthless as you're trying to navigate this complex tree of abstractions to work out how to do something. Examples should really show the minimum amount of unabstracted code required to do something. If you're writing a whole framework to run an example, shouldn't that framework just be in your crate to begin with?

wgpu is guility of this, for example. I mean, look at this whole thing. Should every project be using a EventLoopWrapper and a SurfaceWrapper with suspend-resume functionality, even if they're just making a desktop app? Probably not! I get that these examples are intended to run on every platform including mobile AND the web AND be used for testing/debugging, but at that point it's pretty useless as an example for how to do things. Write something else for that. This is alleviated to some degree by the hello_triangle example, which doesn't use this framework. If it wasn't for that, it'd be a lot harder to get started with wgpu.

ash has the same problem. Yeah I get that Vulkan is extremely complicated, but do you really need this whole piece of helper code if you only have two examples? Just copy that stuff into the examples! I know this violated DRY but it's such a benefit that it's worth it.

egui, same problem. I don't want to use whatever eframe is, just egui with winit and wgpu directly. There are no official examples for that, but there's one linked here. And once again, the example is abstracted into a helper struct that I don't want to use.

AAahhhh. Rant over.

r/rust • • Aug 23 '26

🧠 educational How no_std are no_std crates really? A survey

Thumbnail w-graj.net
159 Upvotes

r/rust • • 27d ago

🧠 educational Visualizing Rust's Vtables: How dyn Trait Works In Memory (Comparison to C++ CRTP & virtual functions)

Thumbnail sofiabelen.github.io
259 Upvotes

I’m venturing into Rust and it’s both satisfying and mind-boggling at the same time. So far I’ve been learning from the book and Mara Bos’ book, but I got the itch to do some dissecting myself. My initial goal of these experiments was to compare Rust’s approach to polymorphism with C++’s. Ultimately, however, as I’ve come to realize, it’s a bit of a trap when trying to understand a new language through another one to try to draw 1:1 parallels. It might seem like it helps, but at the end of the day, we can’t treat Rust as C++ with different syntax. If that were the case, there’d be nothing revolutionary about it.

That said, I believe there is merit in poking around and coming to understand the why. So, if you’re like me and need to know what exactly is happening in memory, in order to feel like you truly understand the concepts, hopefully you’ll find this post useful :)

Edit: Thank you everyone for your kind comments!! And also for the feedback and the chance to deepen my understanding, I'll edit my post with some of the clarifications!

r/rust • • Jan 25 '26

🧠 educational Things I miss in Rust

154 Upvotes

Since most of my previous work was in C++ and C#, I sometimes catch myself missing certain OO features, especially:

  • function overloading
  • inheritance (not even gonna try 😁)

One thing that comes up a lot for me is constructors. I’d love to be able to define multiple new functions with different parameters, something like:

pub fn new(...)
pub fn new(..., extra_property: T)

Right now this usually turns into patterns like new + with_extra_property etc., which work but feel a bit more verbose.

Is there a fundamental reason why function overloading isn’t possible (or desirable) in Rust? Is it mostly a design philosophy or are there technical constraints? And is this something that’s ever been seriously considered for the language, or is it firmly off the table?

Curious to hear how others think about this, especially folks who came from C++/C# as well.

EDIT:
Conclusion: Builders it is.
P.S. Thanks everyone for the insight!

r/rust • • Jun 16 '25

🧠 educational Why is "made with rust" an argument

209 Upvotes

Today, one of my friend said he didn't understood why every rust project was labeled as "made with rust", and why it was (by he's terms) "a marketing argument"

I wanted to answer him and said that I liked to know that if the project I install worked it would work then\ He answered that logic errors exists which is true but it's still less potential errors\ I then said rust was more secured and faster then languages but for stuff like a clock this doesn't have too much impact

I personnaly love rust and seeing "made with rust" would make me more likely to chose this program, but I wasn't able to answer it at all

r/rust • • Apr 06 '26

🧠 educational I'm curious, how often do you use `unsafe` in Rust in prod?

57 Upvotes

I've been learning more about memory layout, unsafe, things like that lately. I'm no expert, so I'm trying to gauge how often people actually have to care about these and how often they actually use them in production vs how much of the code is just safe and fairly normal Rust?

r/rust • • Apr 20 '26

🧠 educational [Blog] Ok, what ACTUALLY uses Rust?

Thumbnail blog.goose.love
144 Upvotes

r/rust • • 18d ago

🧠 educational Principles for fast Tokio applications

Thumbnail dial9-rs.github.io
217 Upvotes

r/rust • • Aug 02 '26

🧠 educational Faster floating point math with Rust’s new API

Thumbnail pythonspeed.com
213 Upvotes

r/rust • • 22d ago

🧠 educational I finally learned how full-screen terminal apps give you your old screen back

83 Upvotes

TIL that terminal emulators basically give programs access to two screens.

There’s the primary screen, which is the normal terminal you use every day. Your shell history and previous output live there.

And then there’s the alternate screen.
Full-screen terminal programs like Vim, less, htop, etc. can switch to this alternate buffer, take over the entire terminal, draw whatever they want, and then switch back when they’re done.
The cool part is that your primary screen is still there.

So when you quit Vim, your terminal suddenly goes back to exactly what was there before you opened it. Vim didn’t somehow “restore” your terminal history. The terminal emulator just switched back to the primary screen buffer.

I came across this while building a small terminal-native text editor in Rust. I needed the editor to take over the terminal while it was running, but leave the user’s shell untouched after exiting.
Turns out terminals already have a mechanism specifically for this.

The deeper I go into terminal programming, the more I realise how much stuff happens underneath that blinking cursor that I’d never thought about before.

I’ve been putting these little Rust experiments on my GitHub as I learn, if anyone’s interested in this kind of low-level stuff:
https://github.com/Abhijeet-Gautam5702/femto

r/rust • • Sep 11 '25

🧠 educational We rebuilt our SQL parser in Rust: 3.3x faster with a zero-copy AST and better diagnostics

436 Upvotes

Hey r/rust

We encountered a massive bottleneck where our SQL parser was taking 13s on a 20s query. We rewrote it from scratch in Rust and wanted to share the architectural lessons.

The key wins came from letting Rust's principles guide the design:

  • Zero-Copy: A fully borrowed AST using &'a str to eliminate allocations.
  • Better Errors: "Furthest-error-tracking" for contextual errors with suggestions.
  • Clean Architecture: Strictly separating parsing (syntax) from analysis (semantics).

We wrote a deep-dive on the process, from our Pratt parser implementation to how the borrow checker forced us into a better design.

Blog Post: https://www.databend.com/blog/category-engineering/2025-09-10-query-parser/

Demo Repo: https://github.com/ZhiHanZ/sql-parser-demo

Happy to answer any questions!

r/rust • • Jul 21 '26

🧠 educational mmap behind the scenes in a database

Thumbnail savannahar68.medium.com
146 Upvotes

I wanted to write this for probably a year now. I've been using mmap in two append-only databases built in rust and this is everything I learned actually understanding it, including why it works in our favor even though Andy Pavlo's paper says mostly don't use it.

disclaimer: A bit of a long read though.

r/rust • • May 06 '25

🧠 educational “But of course!“ moments

169 Upvotes

What are your “huh, never thought of that” and other “but of course!” Rust moments?

I’ll go first:

① I you often have a None state on your Option<Enum>, you can define an Enum::None variant.

② You don’t have to unpack and handle the result where it is produced. You can send it as is. For me it was from an thread using a mpsc::Sender<Result<T, E>>

What’s yours?

r/rust • • Apr 01 '26

🧠 educational Rust on Windows: random crashes turned out to be the default stack size

214 Upvotes

Today, I encountered interesting detail when developing cross-platform program ( GitComet ) written fully in Rust.

Most development happened on Linux, and the app worked fine there. But after using the Windows build for a while, I started seeing what looked like random crashes.

Stackoverflow exception program exit, panic handlers dont run, no stacktrace.

In debug mode on Windows, the crashes became much easier to reproduce.

Increasing the Windows linker stack size to 8Mb fixed the issue:
Reference: https://github.com/Auto-Explore/GitComet/pull/99/changes#diff-519337722c958a057bccc24eada91aeccfc76cd22e0aab01a18a6529a007b8d6

I thought this was interesting learning experiment and wanted to share it with you guys

r/rust • • Aug 03 '26

🧠 educational If you're as pedantic as me, add this Clippy config to your Cargo.toml

171 Upvotes

One of the main reasons I love Rust is because it encourages you to be pedantic.

I admire Clippy and the first things I do after a new Rust version is to fix all their new pedantic lints.

Before important PR merges and releases I always used to run cargo clippy -- -W clippy::pedantic and search for unwraps, expects, panics and other possible clauses that could result in a runtime panic.

Today I decided to make clippy::pedantic my default and to enforce checks on possible panic sites

Probably many of you already know this, but much of this can be made automated by adding a section like the following to your project's Cargo.toml

[lints.clippy]
pedantic = { level = "warn", priority = -1 }
unwrap_used = "warn"
expect_used = "warn"
panic = "warn"
todo = "warn"
unimplemented = "warn"
unreachable = "warn"
dbg_macro = "warn"
print_stdout = "warn"
print_stderr = "warn"

This paired with a cargo clippy -- -D warnings in your CI/CD is a really good combo in my opinion.

The three last lints are just useful in case you want to be sure that you're not forgetting any test print on the terminal.

Each of them can of course be disabled locally on a specific file / method / line with the usual directive #[allow(clippy::name_of_the_lint)]

r/rust • • Nov 09 '25

🧠 educational How can you teach rust to someone who grew up with OOP?

60 Upvotes

I grew up with java, C#, python, javascript, etc. The only paradigm I know is Object Oriented. How can I learn rust? what are the gaps in terms of concepts when learning rust?

r/rust • • Aug 29 '25

🧠 educational A complete map of the Rust type system

Thumbnail rustcurious.com
431 Upvotes

r/rust • • Apr 23 '26

🧠 educational Rust in Production: Jon Gjengset on using Rust in safety-critical systems at Helsing

Thumbnail corrode.dev
243 Upvotes

r/rust • • Mar 02 '26

🧠 educational perf: Allocator has a high impact on your Rust programs

221 Upvotes

I recently faced an issue where my application was slowly but steadily running out of memory. The VM has 4 CPUS and 16GB ram available and everyday about after ~6hours (time varied) the VM gets stuck.

I initially thought I had memory leak somewhere causing the issue, but after going through everything multiple times. I read about heap fragmentation.

I had seen posts where people claim allocator has impact on your program and that default allocator is bad, but I never imagined it had such a major impact on both memory and CPU usage as well as overall responsivness of the program.

After I tested switching from rust default allocator to jemalloc, I knew immediately the problem was fixed, because the memory usage growth was expanding as expected for the workload.

Jemalloc and mi-malloc both also have profiling and monitoring APIs available.

I ended up with mi-malloc v3 as that seemed to perform better than jemalloc.

Switching allocator is one-liner:

#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;

This happened on Ubuntu 24.04 server OS, whereas the development was done in Arch Linux...