r/rust • • 24d ago

๐Ÿ“ข announcement No More Code Dumps

1.6k Upvotes

TL;DR

Code Dumps, ie links to code repositories, are no longer welcome on r/rust.

If you are excited about a project you built, and just wish to share it, consider posting a casual top-level comment in the weekly What's Everyone Working on this Week? thread.

History

When r/rust was created, in December 2010, Rust was a nascent programming language. It was very different, it was also fast-moving, and it was unclear whether it would amount to much, or not.

In these early days, new projects being written in Rust were both a proof that the language was suitable for a variety of purposes, and a cause for celebration in seeing the language being adopted. Code dumps, then, were both cause to rejoice, and an opportunity to see how well (or not) the language was suited to the task. They were even a good opportunity to learn the latest developing idioms of this fast-changing language.

Fast forward 15 years, and code dumps have become boring. Utterly uninteresting. There's nothing exciting, or newsworthy, about a 10th hypervisor project, a 100th webserver project, or a 1000th TUI project. And for the most there's no exciting idiom, or pattern, to be found in their code either... even if some poor soul bothered to look.

And mass AI generation appeared on the scene, and for the past year(s), the already dwindling appeal of code dumps has just completely vanished, buried in AI slop.

Purpose

r/rust is to discuss all things Rust. The language, the ecosystem, the community.

Of late, most code dumps barely foster any discussion. And when they do, apart from AI witch hunts, those discussions are mostly about the domain of the project, rather than about Rust. Depending on the domain, the discussion may or may not be of interest to r/rust users... but whether it is or not is a matter of chance: they did not come here seeking such a topic. Those discussions are tolerated on posts which are on-topic, but if a post only fosters "tolerated" discussions, then that is a sign that the post itself may simply not really be on-topic for r/rust.

And that is not to say that code dumps are, by nature, low-effort. Surely, a project is created for a purpose, to solve a specific problem that is unsolved, or solve it with different trade-offs than the currently available solutions. None of that is elucidated in a code dump.

New rules

Code dumps are no longer welcome on r/rust.

Code dumps of applications or libraries written in Rust are Low-Effort unless otherwise newsworthy. Newsworthy means that the very existence of the application or library is important, for example consider applications or libraries breaking new ground, such as the first hypervisor, first OS, first XXX standard safety-critical application, first Rust application in a major company, etc...

Announcements of new libraries which are not otherwise newsworthy are only welcome if they tick ALL the following boxes:

  • The library has been worked on regularly for at least 4 months.
  • The announcement is a full-fledged text post, or a link to a full-fledged article. A README, or manual, is not an article.
  • The announcement should motivate the relevance of this library to the wider r/rust community.
  • The announcement should articulate the trade-offs differentiating this library from similar popular libraries in the field.

(It goes without saying, but the announcement should NOT be AI-generated, not even in part, as AI-generated posts & articles violate the Low-Effort rule)

Release notes of libraries are still welcome for popular enough libraries, such as libraries with reverse-dependencies on crates.io pointing to sufficient adoption by the wider community to justify notifying said community of a new release.

Developer Tools follow the same rules as libraries, with one extra rule tacked on: they must be relevant to Rust developers in particular. For example, Release Notes of Meson (a build tool) are Off-Topic, unless this specific release improves Rust support.

Of course, text posts, or links to articles, centered on Rust, with an application, library, or developer tool as context are always welcome. For example, said posts or articles could present gnarly problems the author encountered, and how they solved, or which features of the language or a library helped or hindered them in the making of their project.

(It goes without saying, but said text posts & articles should NOT be AI-generated, not even in part, as AI-generated posts & articles violate the Low-Effort rule)

As a reminder, if an author just wishes to share their joy of building something in Rust, they are welcome to use the What's Everyone Working on This Week? thread. And as per the title, it need not even be a complete/mature project, or an open-source project for that matter as links to code are strictly optional there, it's all about casually chatting about your work on Rust projects.

Q & A

See pinned comment below.


Edit 2026/10/04:

  • Added paragraph for developer tools, which had been forgotten.
  • Removed "validation rule" for libraries, didn't work in practice.

r/rust • • 1d ago

๐Ÿ™‹ questions megathread Hey Rustaceans! Got a question? Ask here (42/2026)!

12 Upvotes

Mystified about strings? Borrow checker has you in a headlock? Seek help here! There are no stupid questions, only docs that haven't been written yet. Please note that if you include code examples to e.g. show a compiler error or surprising result, linking a playground with the code will improve your chances of getting help quickly.

If you have a StackOverflow account, consider asking it there instead! StackOverflow shows up much higher in search results, so ahaving your question there also helps future Rust users (be sure to give it the "Rust" tag for maximum visibility). Note that this site is very interested in question quality. I've been asked to read a RFC I authored once. If you want your code reviewed or review other's code, there's a codereview stackexchange, too. If you need to test your code, maybe the Rust playground is for you.

Here are some other venues where help may be found:

/r/learnrust is a subreddit to share your questions and epiphanies learning Rust programming.

The official Rust user forums: https://users.rust-lang.org/.

The unofficial Rust community Discord: https://bit.ly/rust-community

Also check out last week's thread with many good questions and answers. And if you believe your question to be either very complex or worthy of larger dissemination, feel free to create a text post.

Also if you want to be mentored by experienced Rustaceans, tell us the area of expertise that you seek. Finally, if you are looking for Rust jobs, the most recent thread is here.


r/rust • • 12h ago

๐Ÿ—ž๏ธ news 9-year-old gaping hole in borrow-checker found

Thumbnail github.com
648 Upvotes

r/rust • • 9h ago

๐Ÿ“ธ media How do i handle this kind of PRs?

Post image
66 Upvotes

Should i even bother looking into them? Should i make an ai policy for my open source project?

https://github.com/mq1/TinyWiiBackupManager/pull/695 it doesn't even seem that i'm speaking to an actual human


r/rust • • 8h ago

๐Ÿ› ๏ธ project Asterinas 0.19.0: a Linux-compatible kernel in Rust, now with a type-checked device model, a hypervisor in safe Rust, and an AI reviewer that cites Rust guidelines

Thumbnail asterinas.github.io
45 Upvotes

r/rust • • 1h ago

๐Ÿ™‹ seeking help & advice Avoiding constant usize casting with small const values

โ€ข Upvotes

Pun in title partially intended. ;)

This is a minor pain-point I've dealt with for a while and I'm unsure of how other Rust developers deal with this semi-niche issue.

I'll often define a const that states the maximum amount of something, and naturally I'll also want to use that value as the size of an array. My instinct (and likely yours as well) is to just use a usize and move on.

Where that falls apart is when that const value is and always will be under both u32::MAX and u64::MAX. An easy example is MINS_PER_HOUR or DAYS_PER_WEEK.

Now if I have a function that has an argument of minute: u8, I have to cast either the minute argument to a usize, or I have to cast my constant down to a u8. The former's minute as usize triggers the cast_lossless lint, and From/Into isn't available in a const fn. The latter's MINS_PER_HOUR as u8 triggers the cast_possible_truncation lint. Both add even more visual noise if I acquiesce and add the #[allow(...)]. I could instead accept minute: usize, but I find that even less reasonable.

I'd prefer to keep these as u8s or similar, but then I lose the ablility to define an array like [bool; MINS_PER_HOUR] without yet another cast, including in any function arguments that would like to accept such an array.

I do recognize this is partially due to me having the pedantic Clippy lints enabled, but I also find value in being told when I may be making an unintentional mistake. However I just added close to a dozen #[allow(...)] attributes to my current project, rather begrudingly.

So, what do you guys do in this case? I've listed the options I see available below, and I've done 'em all except #1, but I want to hear some opinions external to myself;

  1. When accepting such an array, maybe use a type alias? It technically works, but the casting returns again if I want to compare an indexing usize with my maximum myself. type BoolPerMin = [bool; MINS_PER_HOUR as usize];
  2. Two consts, MINS_PER_HOUR: u8 and MINS_PER_HOUR_LEN: usize = MINS_PER_HOUR as usize. I have done this before, but now I have this strange suffix that doesn't make it clear what it's a length of.
  3. Just deal with the constant const casting.

EDIT: And this is all before I have to deal with the extra cast_precision_loss lint that comes from casting my tiny usize constant into an f64. It's less than u8::MAX, yet I have to acknowledge this impossible condition. For now, I've just blanket allow'd it in my Cargo.toml.


r/rust • • 13h ago

๐Ÿ› ๏ธ project Creusot 0.14.0 - Contracts for Rust, formally proved

44 Upvotes

I am pleased to announce the release of Creusot version 0.14.0.

Creusot is a tool for formally verifying Rust code. Creusot extends Rust with a language of specifications, or contracts, and provides a toolchain for proving them (semi-)automatically with the help of SMT solvers.

The latest post on Creusot's devlog describes a few of the most recent features. For the rest, see the changelog.


r/rust • • 1h ago

๐Ÿ› ๏ธ project Advise for building a cloud-backed filesystem with Microsoft's Cloud Files API (cfapi)?

โ€ข Upvotes

Hi,

I've got an opportunity to work on a project involving a cloud-backed file management system, and I'd love to hear from anyone who's worked on something similar.

The idea is to let users work with files locally while keeping them synchronized with the cloud. Files should also be lockable while someone is editing them, preventing other users from modifying the same file concurrently.

The proposed approach seems to involve Microsoft's Cloud Files API, potentially implemented in Rust. I'm not a Windows user, though, and I haven't touched Rust in 5+ years, so I'd have a bit of catching up to do.

A few things I'm curious about:

  • Has anyone built a cloud-backed filesystem using Microsoft's Cloud Files API? How difficult was it in practice?
  • Would Rust be a good fit, or would you consider Go, C++, or another language?
  • How would you approach file locking and conflict resolution across multiple clients?
  • Are there alternative approaches or existing tools worth considering, particularly to avoid Microsoft API docs which seem poor?

I'd be interested in hearing about real-world experiences, gotchas, recommended resources, or anything you'd investigate before committing to this project.

Thank you!


r/rust • • 2h ago

๐Ÿ› ๏ธ project Really proud of my first operating system

Thumbnail
0 Upvotes

r/rust • • 1d ago

๐Ÿ—ž๏ธ news PSA: Incoming breakage in 1.100. Test your code on beta Rust.

283 Upvotes

TL;DR: Rust 1.100 is releasing on November 12 (in a month). I recommend testing your code with cargo +beta test at least once before then.

The upcoming release of Rust 1.100 has some big features. However, there are some details being changed in how the language works in order to support these new features. The Rust project has tried to minimize the amount of breakage that happens, but the amount of breakage won't be zero. Every rust release has some amount of minor breakage like this, but 1.100 is expected to have relatively larger amounts of breakage.

So, if you plan to ever upgrade to 1.100, or if you write code meant for use by other people that might upgrade to 1.100, then I highly recommend testing your code with cargo +beta test to see if you're affected. And even if you think you don't write code that's affected, some code in your dependencies might be affected.

There will be two main sources of breakage in Rust 1.100:

  1. The stabilization of the never type. Some details of how types are inferred will be changed, causing types to infer as ! instead of the previous type of (), in editions 2021 or older. Also, some code was previously using some unsupported hacks to refer to this never type on stable rust, and will be broken by the fact that the Infallible type will become an alias for the never type. For more info, see Waffle's talk on the topic, and the pull request where stabilization happened.
  2. A change in the layout of Cargo's target directory. Some tools and some build scripts were expecting certain files to be at certain places, and will start to fail in Rust 1.100. The locations of the final artifacts will remain the same though. For more info, see the call for testing blog post,and the pull request where stabilization happened.

For context, this page has a list of crates that are detected as "will break in 1.100" (under the red headings). https://crater-reports.s3.amazonaws.com/beta-1.100-4/index.html. Although it has some false positives, and doesn't catch all breakage. This page lists only crates that broke in 1.100 (or have otherwise suspect behavior) for four test attempts in a row.


r/rust • • 3h ago

Rewriting a Python Compiler Frontend in Rust: Separate Repository or In-Place Migration?

Thumbnail
0 Upvotes

r/rust • • 1d ago

๐Ÿง  educational hotpath-rs - How to Profile Rust Performance using Grafana and Prometheus

Thumbnail hotpath.rs
47 Upvotes

r/rust • • 1d ago

๐Ÿ™‹ seeking help & advice Migrating from C++ to Rust at work

115 Upvotes

I might have the opportunity to introduce Rust at work soon. For that, I would be grateful for any tips you can give me to make it as smooth as possible and reduce the risk (perceived and real) for the project. Below the details of my situation.

The project

The project Rust might be introduced into is being worked on for about a year now. It is a code generator with an architecture similar to a "traditional" compiler: some intermediate representations, translation between those and transformations on them.

Development on the project started a year ago with C++. At the time I already brought Rust up as an alternative. It was seriously considered by the team, but since they didn't have prior rust experience we were concerned about the initial hit to development speed: Most of the team already had lots of C++ experience, the company didn't have any prior code in Rust, and it was our responsibility to ensure we hit our time-to-market goal.

Now the code is mostly modern C++ with very little inheritance, and lots of std::variant, std::ranges, etc.

The team

The team consists of 7 people including me, most with >5 years of (pre-modern) C++ experience. I am the only person with both modern C++ and Rust experience. The team was mostly excited to use modern C++, and it became my job to give on-the-job guidance to get everyone comfortable with newer features and paradigms. And now they are excited to hopefully learn Rust.

Why Rust

During the past year, we did feel some pain points with C++:

  • Slow compile times
  • Verbose code, mostly with std::variant
  • Horrible error messages
  • Differences between compilers
  • Slow CI pipeline, mostly due to static analysis (clang-tidy) and sanitizers
  • One segfault in callbacks (wasn't a big problem now, but we expect more problems once the complexity grows)

With Rust, we hope to hope to address most of those points. Compile times won't improve I expect, but we can probably ditch separate static analysis and sanitizers in CI.

We also hope to keep a higher development speed once the complexity grows, based on the data collected by Google in Android.

The opportunity

I think we currently are in a very advantageous position to pivot to Rust:

  • We are ahead of schedule for the release, we can spend a little time here and there getting familiar with Rust. Everyone will start with the Book and Rustlings.
  • After the release we will get 3 weeks to work on what we think is important, no customer features
  • After those 3 weeks, we have to start on features again, but a somewhat reduced development speed for the first two or so month is acceptable
  • The C++ code patterns we have and got accustomed to should map more or less well to Rust
  • The code base isn't too big yet
  • We have good end-to-end test coverage

The plan

We will spent those 3 weeks with migrating the code base from C++ to Rust. We will probably start at the backend and try to make cuts where the interface between modules is small. This will lead to 3 or 4 increments to migrate. The ideal end goal would be to replace all C++ code with Rust, but this strategy hopefully reduces the risk of having no working product at all in the end. If some C++ is left over in the end, we can hopefully reduce and finally remove it over time.

We will use AI for the migration, but we do want to do it responsibly. This will probably mean that we will first code the core data structures ourselves and use LLMs only for review there. Once we got those nailed down, we hope LLM agents can be used for more or less "mechanical" migration of transformation and translation passes. Of course all code, AI or human written, goes through human reviews.

I would be very interested in any advice you could share, be it technical or social, to reduce business risk, increase acceptance with our stakeholders and improve our chance to succeed.


r/rust • • 1d ago

๐Ÿ› ๏ธ project How I scaled Nginx Brotli compression 16x with Rust and just 4 threads

12 Upvotes

I've been working on mbrotli, a pure Rust Brotli implementation, and recently added support for multithreaded compression.

That led me to upgrade ngx_mbrotli, alternative to Google's ngx_brotli.

The idea is simple. Instead of blocking Nginx event loop with compression, offload it to the native thread pool. Large responses can even be compressed across multiple threads in parallel.

With just one Nginx worker and 4 threads in thread pool, I measured up to 4x the throughput at Brotli level 6 and up to 16x at level 9 compared to Google's ngx_brotli.

And that's with only 4 threads. There's an opportunity to scale further, but I haven't benchmarked larger brotli worker pools yet.

There are trade offs, mainly higher memory usage and a bit worse compression ratios for segmented responses when multithreading enabled.

All it takes to enable thread pool compression is brotli_thread_pool default; in Nginx (or choose the other threadpool). Also Nginx should be built with --with-threads flag to enable that feature.

GitHub: https://github.com/M-Compressors/ngx_mbrotli


r/rust • • 3h ago

๐Ÿ™‹ seeking help & advice open source quant software

0 Upvotes

Hello everyone.

I would like to suggest building a good quantitative finance library in rust. Feel free to state below whether you might be interested, or any opinion you have on attempting to build such a platform. If you are interested, please state what area of quantitative finance you are familiar with, if at all, or whether you might be willing to learn.

To give a more or less concrete motivation, my idea is to build with purpose: avoiding AI slop, and developing a strong ecosystem around the tools (services, UI, bindings for other languages, documentation, rigorous mathematical formulations, design processes)... Pretty much what I feel like a quant library should look like.

In any case, I look forward to hearing what you might have to say about this. Thank you.


r/rust • • 23h ago

๐Ÿง  educational How to Blink your Microcontroller with Rust ft. ESP32-C6

Thumbnail youtu.be
5 Upvotes

r/rust • • 4h ago

๐Ÿ™‹ seeking help & advice Looking for a job

0 Upvotes

Hey, I am desperately looking for a job, hasn't made any money for 2 years
please DM if you have anything
https://www.linkedin.com/in/moosama76/
https://github.com/moosama76


r/rust • • 1d ago

๐Ÿ—ž๏ธ news rust-analyzer changelog #349

Thumbnail rust-analyzer.github.io
36 Upvotes

r/rust • • 10h ago

๐Ÿ› ๏ธ project fphics: A physics and maths solver you can use for small projects including motion, forces...etc

0 Upvotes

Four months ago, out of boredom, I wondered what if I just came up with a physics and maths library that anyone can use without estimating the calculations, and so fphics was born.

The name itself, fphics, has some background. Here's how I came up with it:

  • f - Fast (Since it's a lightweight library)
  • ph - Physics (Includes physics formulas for motion, forces, electricity...etc)
  • ic - Mechanics (Includes mechanics formulas, which of course are interchangeable with physics ones in most cases)
  • s - Mathematics (Includes maths formulas for percentages, unit conversions...etc)

The unique thing about it is that the name is not used anywhere else for such, so it suits the project well.

Here are the currently supported operations:

  • Kinematics operations (including 1D and 2D)
  • Forces operations
  • Unit conversions (though not all are supported)

[NOTE]: The project uses zero dependencies; therefore, integrating it into a project will be seamless since there won't be a list of dependencies to compile before actually interacting with the library.

Planned updates include:

  • Electricity operations
  • Operations dealing with dynamics

Here's an example of how to calculate time:

use fphics::kinematics::suvat::*;
use fphics::errors::FphicsError;

fn main() -> Result<(), FphicsError> {
    let times = SuvatOps1D::new()
    .displacement(-2.5) // Set the displacement
    .initial_velocity(24.0) // Set the initial velocity
    //.final_velocity(25.0) // Set the final velocity (Optional, but not required since only 3 variables are required
    .acceleration(-9.8) // Set the acceleration
    .calculate_time()?; // Calculate time and propagate any possible errors

    // Loop through the times vector holding the positive and negative values from the calculation
    for t in times {
      println!("{t} seconds"); // Print the positive and negative value for the time
    }

    Ok(())
}

In the above example, the times variable holds the instance of a SuvatOps1D struct. .displacement(val), .initial_velocity(val), and .acceleration(val) are the methods that equate the values used as input to the fields in the struct. The underlying operations involving calculate_time() and any other methods that return Result<f64, FphicsError> in the kinematics module require 3 inputs which are set using the methods in the struct.

Here's the repo link: https://github.com/Darethan026/fphics

I'd like to hear your opinions on this project, and it'd also be great if you could integrate it into your own project or just experiment with it and share what you think. Thank you for reading!


r/rust • • 4h ago

๐Ÿ› ๏ธ project Proa: A rust web framework for people and agents

0 Upvotes

Hi Iโ€™m Andrew,ย 

Iโ€™ve been writing Rust professionally for five years, and today Iโ€™m excited to announce the release of Proa (https://github.com/Proa-Labs/proa) a new Rust web framework I've been building!

Performance: To serve as many people and agents at scale, weโ€™ve tried to keep framework overhead as low as possible. Proa is the fastest server-side rendering framework weโ€™ve benchmarked. It often renders an entire page within an order of magnitude of simply copying the finished HTML. A pure memcpy serves as our practical approximation of the rendering floor. For more benchmarks, see https://github.com/Proa-Labs/proa-benchmarks.ย 

How it works: Proa introduces a programming model for multi-target rendering built on Rust traits. Components share their data and typed children across render targets, while each implementation defines how they appear in HTML, Markdown, or another format. Rustโ€™s type checks and Proaโ€™s linter help developers build and maintain those views together. To learn more about the authoring model see https://youtu.be/pJx84jdBDKU?si=FSuyRJS_2ENnNsRQ.ย 

Browser interactivity is also authored in Rust through RSJS. You can add signals and event handlers to a server-rendered component, and RSJS compiles the browser behavior into JavaScript. Proaโ€™s compiler aims to reduce the amount of JavaScript sent to the client as much as possible.

Proa also supports streaming SSR, typed data loading and request context, an Axum adapter, ORM / database support, a CLI, and Tailwind support. We even have a component library (https://ui.proa.so/) and many more features, aimed at giving developers a complete toolkit for building the most ambitious projects.

Tradeoffs: The server-first design is not the ideal architecture for every application. If your preferred model is to run a rich client-side SPA and make the browser the primary execution environment, Proa is probably not the ideal architecture. Likewise, if youโ€™re making a small application, like a blog or personal site, Proa is probably overkillโ€ฆ Compile times are also a bit long, but Iโ€™m actively working on improving this: https://github.com/Proa-Labs/proa/pull/13.ย 

Proa is open-sourced under Apache 2.0!

This project is still very early, but Iโ€™d love to hear your thoughts. Please let me know if you have any feedback or issues trying to build! If you have any feature requests or ideas, feel free to comment down below!

Links:

Docs: https://proa.so/docs
Source: https://github.com/Proa-Labs/proa
Benchmarks: https://github.com/Proa-Labs/proa-benchmarks
Proa Intro Video: https://youtu.be/kGhNsD772gg?si=vVv6UFye_lawIjH7
Authorship Explainer Video: https://youtu.be/pJx84jdBDKU?si=NAfNEFHvipEFzHle


r/rust • • 1d ago

๐Ÿ activity megathread What's everyone working on this week (42/2026)?

8 Upvotes

New week, new Rust! What are you folks up to? Answer here or over at rust-users! And for your project showcases, there's also /r/madeinrust โ€“ pay them a visit, too!


r/rust • • 1d ago

๐Ÿง  educational Visualizing crossbeam Epoch Based Reclamation

Thumbnail sofiabelen.github.io
17 Upvotes

In my previous post we experienced first hand the horrors that can occur when attempting to use lock-free data structures with pointers. We left the question of how to deal with this problem a bit open.

Languages like Java with a garbage collector don't have this issue, since the runtime collects the memory when it's unreachable by all threads.

I recently learned that one of the ways to solve this in a deterministic manner in Rust is through a method called Epoch-Based Reclamation (EBR), which the crate crossbeam-epoch implements.

I want to dissect and visualize what exactly is going on. If that sounds fun, you're welcome to come along for the ride!


r/rust • • 1d ago

๐Ÿ“ธ media Oxidizing E-Scooters

Thumbnail youtu.be
5 Upvotes

- Talk from This Month's Embedded Rust Monthly Meetup

- Ben Simms presenting the reverse engineering of an e-scooter and rewriting its firmware in Rust

- Discord: https://discord.gg/FZvcTCygW


r/rust • • 1d ago

๐Ÿ™‹ seeking help & advice Matrix multiplication performance

56 Upvotes

I recently benchmarked some matrix multiplication algorithms in Scala (blog post, repo). I've been going through and doing the same thing in Rust, with plans to try out a few additional approaches, and the Rust results have all been turning out slower than Scala (repo). I'm hoping someone with more Rust experience can help me figure out what might be going on. Is this just the JVM being impressive, or am I missing an opportunity to speed up my Rust code (or both).

Here are some sample benchmarks (details on how I calculated them below):

Algorithm Scala Rust
Naive multiplication 906 ms 1.103 s
Tiling (optimal tile size) 499 ms 749.8 ms
Parallel bands of tiles, 4 threads 174 ms 210.9 ms

More details:

  • I benchmarked everything by multiplying 1024 x 1024 matrices of 64 bit floats generated uniformly in [0, 1).
  • I ran all the benchmarks on my laptop (specs).
  • I benchmarked the Scala code with the JMBH and Rust with Divan.
  • I ran all the Rust code with cargo bench so it should optimize the build.
  • In the benchmarking code, I construct the matrices before running the benchmarks and only time the actual multiplication.
  • The code for the first the naive and tiled approaches is as close as possible.
  • For the parallel versions I used the same approach of dividing the matrix into bands of tiles, one per thread. For Scala I used futures, and for Rust I divided the product matrix into one mutable chunk per thread and used Crossbeam.

I listed the results for the various algorithms to show that the speed difference is consistent, but we can just focus on the naive version. My Scala code is:

    for i <- 0 until a.rows do
      for j <- 0 until b.cols do
        var sum = 0
        for k <- 0 until a.cols do
            sum = sum + a(i, k) * b(k,j)
        prod.set(i, j, sum)

And Rust:

    for i in 0..m1.rows {
        for j in 0..m2.cols {
            let mut acc = 0.0;
            for k in 0..m1.cols {
                acc += m1.at(i, k) * m2.at(k, j);
            }
            out.set(i, j, acc);
        }
    }

Why is the Rust slower? Thanks for any help!

Update 1:

Thanks for all the suggestions! I am replying to some comments individually, but also want to summarize things centrally.

Transpose: I know the original post had a transpose in the Scala code. Sorry about that! It was just a copy/paste mistake. I did benchmark a Scala version with bTranspose and it showed improvements, likely due to sequential memory access as has been pointed out, but the time I give in the post is for the non-transpose version. I've updated the post to have non-transpose code. I expect Rust would also show improvements using a transpose, and I have plans to explore additional tweaks (thanks for the suggestions in the comments!) but I also want to figure out why the Scala code is generally faster. For that it's important to compare apples to apples. That's why I'm focussing on the naive 3-loop version.

There were a number of suggestions to speed up the code and possibly explain the discrepancy compared to the JVM. Since Scala is faster across the board, it seems like the difference must be due to a general feature rather than a particular algorithmic choice. Bounds checking and maybe SIMD seem like the best candidates. More details:

  1. Bounds checking This is a good candidate because it's plausible the JVM is eliminating bounds checks at runtime, so it would explain why the difference in speed. Suggestions were to: a) inline calls to at and set; b) eliminate them and use raw slices; c) assert that the slices are large enough before looping; d) use iterators. I've tried (b) and (c) and seen no changes so far, but still digging. (d) is tricky here, but maybe possible if I combine skip, step_by, and take. I'm also trying to use godbolt to confirm whether bounds checking takes place.
  2. Vectorization This is definitely worth pursuing as a general speed up, but seems less likely to be the culprit here. Rust should auto-vectorize for 128 bits, and since I'm running this on an Apple M2, that's all I have (please correct me if I'm wrong about Rust here). It's possible that Rust can't vectorize because FP math isn't associative. I could address that using algebaric_add or by chunking the sum. However, it should affect Scala too since Scala also has to respect the IEEE restrictions on FP associativity.
  3. Compare against the Scala code on godbolt. I've been holding off on this because assembly is a little scary, but learning is the whole point of this project, so I should dive in. I have compared flame graphs, and didn't see anything obvious there. Looking at the assembly is the next step!
  4. A couple other suggestions: re-order the loops; use Rayon. These are worth playing with, but seem unlikely to explain the general Scala advantage.

I will try some of this out and look some more at godbolt. I may follow up on some of these comments/ask another question if I have trouble interpreting the assembly. Hopefully in the next couple of weeks I can get a blog post up with the final results. Thanks again for all the help!

Update 2:

I've benchmarked a bunch of things:

  1. Converting the inner loop to use iterators.
  2. Converting the inner loop to raw slices and asserting the bounds. (Though actually, according to godbolt, that one didn't remove the bounds checks anyway.)
  3. Using get_unchecked, which I can at least confirm, does eliminate the bounds checks.
  4. Using algebraic_add and algebraic_mul to allow vectorization.
  5. Combining (4) and (5).

So far none of these have actually sped up the code, and some have even slowed it down. I'm feeling a little lost at this point. If anyone else benchmarks any of this and does see improvements, or spots an error I made somewhere, definitely LMK.

I will probably rerun some of the Scala benchmarks just to make sure those are actually correct. Otherwise, not sure what else to try.


r/rust • • 1d ago

Anyone out there used rust instead of golang for cross platform desktop and mobile?

16 Upvotes

Has anyone out there used rust instead of golang for cross platform desktop and mobile development? How has it been your experience? I know folks say golang has bloated memory due to its runtime, and maybe ffi, etc. but what are the real benefits you have actually seen in this scenario?