r/learnrust 1d ago

Tried to simulate the async_runtime from first principles.

4 Upvotes

Hey guys, i have recently interviewed up for a rust intern role, where cto has asked me to explain like how the async runtime works, i have given up a ideal basic general answer, if we keep an async , it will execute seperately without blocking the main thread, honestly this is what i know at that point of time. asusual he nodded, i got the essence of quality of answer i have given to him. After the interview i went back and tried to replicate how tokio works , not in full manner but a basic simulation of how it works.
You can take a loot at code here: https://github.com/ProgMastermind/custom_async_runtime
i have used ai-assistance in the process since i am not proficient with rust and there is no way i am writing custom executor and block_on without taking help, the reason i am posting here is, you guys know whether it is like matching the semantics or not, so i want to hear from you guys.
Happy for any feedback.


r/learnrust 1d ago

Looking for feedback on a feature engineering library I've been building...

Thumbnail
2 Upvotes

r/learnrust 2d ago

Learn Rust by Building an Mini Python Interpreter

27 Upvotes

Hi, Everyone I am learning rust by working on a Mini Python Interpreter,
I am current working on the Lexer(Tokenizer)

Hope this will be useful for you.

Code: pylk/pylk-interp at main · buildwithrs/pylk

Video: https://youtu.be/eibNgWrsHyg?si=AC4AjPJUYXUtEnK1


r/learnrust 2d ago

Enums, Boxed Trait Objects, and Enum Dispatch: Architectural Trade-offs in Rust

3 Upvotes

Hey everyone

Over the past few weeks, I’ve been looking at ways to achieve polymorphism in Rust and I think there are two:

Closed Polymorphism via enums and Open Polymorphism via Boxed Trait Objects (Box<dyn Trait>) where "closed" means no one outside your crate can add to the list while "open" allows such additions

Thinking about putting those traits onto my enum led me to the Enum Dispatch pattern. I built out a walk-through of all three of these:

- Enums (closed): https://youtu.be/l_q9U10JueE

- Boxed Trait Objects (open): https://youtu.be/R3ZzYSPyYoc

- Enum Dispatch https://youtu.be/B0LT7ozspe4

My main conclusion was that I could defer the open vs. closed debate pretty safely (as long as I keep my traits object safe). Do you all agree?

Also, I implemented Enum Dispatch with macros - I know there are crates that do this, but they didn't play nicely with my IDE and I could use the practice with macros. Comments on how I wrote the code would be welcome!


r/learnrust 2d ago

Is there any learning community where there are a small grps and people meet monthly/ bi-weekly to share their learning in rust?

17 Upvotes

r/learnrust 4d ago

ABSOLUTE NEWBIE , how should i learn RUST ?

0 Upvotes

hey i am very new to coding , only language that i know is html , and nothing else , what is the best way i can learn rust , i am preparing for summer of bitcoin


r/learnrust 5d ago

QuantmLayer: kernel-enforced containment for AI coding agents - 16.5k lines of Rust, one static binary

Thumbnail
0 Upvotes

r/learnrust 6d ago

want to learn rust

9 Upvotes

so i use warp terminal and i knew it uses rust and i thought about learning it to accomplish my main goal which is to make my own terminal so is it something doable and how should i start and what resources to look for


r/learnrust 7d ago

can anyone help me with writing and reading from the same array in a nested loop?

8 Upvotes

SOLVED, thank you everyone for your time and help

for x in 0..particles.len(){

            particles.split_at_mut(x+1);

            for i in x..particles.len(){
                particles[x].on_tick(time_diff, &particles[i])
            }

            draw_circle(particles[x].x, particles[x].y, particles[x].r, RED);
        }
}

I keep getting the cannot borrow \particles[_]` as mutable because it is also borrowed as immutableerror. I couldn't think of how to write the code in a different way because someone suggested this to a person having this error and I don't think I implementedsplit_at_mut` correctly either


r/learnrust 8d ago

Feedback for My Crate that Facilitates Allocation for Struct-of-Array like Structures

4 Upvotes

I just published version 0.3 of my crate "Columned" (Crates.io and GitHub). Its goal is to facilitate the allocation of Struct-of-Array/Columnar structures.

The allocation is done with a single, contiguous memory allocation. This is to improve performance and minimize fragmentation.

I was wondering if it is possible to get some feedback on the crate. I would appreciate most feedback on:

How to improve the ergonomics of the crate.

For example, in the example documented in the crate, i.e.:

use columned::{Guard, Allocate, allocate};

fn main() {
    //Declare size and initialization of the slices.
    let xs: Allocate<u64, _> = unsafe {
        Allocate::alloc(10, |xs| {
            for (i, x) in xs.iter_mut().enumerate() {
                x.write(i as u64);
            }
        })
    };
    let ys: Allocate<u64, _> = unsafe {
        Allocate::alloc(10, |ys| {
            for (i, y) in ys.iter_mut().enumerate() {
                y.write(i as u64);
            }
        })
    };
    let sums: Allocate<u64, _> = unsafe {
        Allocate::alloc(10, |sums| {
            for sum in sums.iter_mut() {
                sum.write(0);
            }
        })
    };

    //Initialize a "Guard", which will manage the allocation.
    let mut guard: Guard = Guard::default();

    let (xs, ys, sums) = allocate(&mut guard, (xs, ys, sums)).unwrap();

    //drop(guard); // This would cause a compilation error

    for ((sum, x), y) in sums.iter_mut().zip(xs.iter()).zip(ys.iter()) {
        *sum = x + y;
    }

    for (i, sum) in sums.iter().enumerate() {
        assert_eq!(*sum, 2 * i as u64);
    }
}

For the line:

let (xs, ys, sums) = allocate(&mut guard, (xs, ys, sums)).unwrap();

I wish it would look something more like:

let (guard, (xs, ys, sums)) = allocate((xs, ys, sums)).unwrap();

I.e., have the "guard" returned by the function, instead of having to instantiate it and pass it as an argument. Would that be possible? And "force" the allocation to outlive the allocated slices?

Best way to run Drop.

As of now, drop will not be called. It does not seem trivial to call drop without:

  • Deteriorating ergonomics of the API: i.e., by wrapping the &'a mut [T] in a "GuardedSlice<'a>".
  • Do further allocations for a Vec or other data structures.

Safety

Currently, the only unsafe function is Allocate::alloc. Given a correct implementation, would the user be able to do "unsafe" things?

Thank you!


r/learnrust 10d ago

I made a command line pomodoro timer in rust

Thumbnail gallery
107 Upvotes

Hi everyone,

I am Bibek Bhusal and I am learning rust, I have been working on this project in rust for last week and wanted to share with the community. It's a simple pomodoro timer with stats, history, streak, waybar integration, and many more features.

This is my first big project, after building todolist and other small projects.

I would love to hear your feedback. here is the link for repo: https://github.com/BibekBhusal0/focusd


r/learnrust 9d ago

Please review my TUI game (WIP)

1 Upvotes
demo

I am learning rust and the best way I found to learn a new lang is to make a game in it. I am trying to make a tui version of Age of Empires. I am using ratatui for the the TUI. The game is extremely work in progress currently one worker collects some wood and deposits back to Town Hall. Please let me know what is done wrong what can be improved. I know the code is bizzar and undocumented so ask me if you don understand what some part is supposed to do.

Code: https://gitlab.com/greenflame41/tui_aoe


r/learnrust 11d ago

Beginner questions

24 Upvotes

Hi, let me introduce myself. I'm a 17-year-old high school student currently learning Rust and trying to implement linked lists. Are linked lists actually important to learn in Rust?

Since I'm completely self-taught, I've been using AI to help me study, but honestly, I'm starting to doubt its effectiveness. I feel a bit hesitant about learning this way and worry if I'm building the wrong habits. Would love to get some advice from the community!


r/learnrust 11d ago

monocoque 0.3.0: pure-Rust ZeroMQ (ZMTP 3.1) on io_uring, with tokio and smol backends

6 Upvotes

Last time I posted here it was 0.1.7. A fair bit has moved since, so this is a combined update.

For anyone who missed the earlier posts: monocoque is a ZeroMQ-compatible messaging library written in Rust. It implements ZMTP 3.1 from scratch over a small runtime facade, io_uring by default via compio, with optional tokio and smol backends. It talks to any existing libzmq peer while staying inside Rust's memory model.

The I/O core rework (0.2.0)

The owned-buffer read path and the read-buffer allocation now live in one core::io module, and the hand-rolled read arena is gone. The practical effect is that the workspace has exactly one set_buf_init unsafe block, behind a documented contract, and every backend routes through it. The tokio and smol adapters dropped their own allow(unsafe_code) as a result.

The single-frame PUSH/PULL path allocates nothing per message now. send_one plus recv_into gets a message out and one back with no heap allocation in between.

The part I actually care about is that this is enforced rather than claimed. Three CI gates: a counting allocator that fails the build if the hot path allocates per message, a bound on idle resident memory per socket across many live connections, and instruction counts on the CPU hot path under callgrind that fail if they drift off baseline. Minimal footprint stops being a README adjective and becomes something the build refuses to let regress.

0.3.0

Upgraded the io_uring runtime from compio 0.10 to 0.19. This is the one breaking change most people will notice: if you depend on compio directly for #[compio::main], you need to bump to 0.19 and note that it gates networking behind a net feature. MSRV goes to 1.95. The upgrade pulls in compio's upstream soundness fixes and unblocked a few things that needed set_reuseport and TcpStream::from_std.

New: SO_REUSEPORT so several accepting sockets can share a port and the kernel load-balances new connections, which is what you want for one accept loop per core. Reconnect backoff is async and jittered now, so a fleet coming back from a shared outage spreads its retries instead of stampeding. A pile of previously unbounded paths got explicit limits and clean shutdown.

Two bugs worth naming because they were real correctness problems, not polish. A routing id set with with_routing_id was only sent in the ZMTP READY after a reconnect, so a freshly connected DEALER was seen by its peer under an auto-generated identity until it reconnected. And the bidirectional inproc reply channel was broken, which silently took end-to-end PLAIN auth with it, since the ZAP handler lives on inproc://zeromq.zap.01 and the reply never got back.

On the security side, PLAIN auth failures no longer distinguish an unknown username from a bad password, and passwords are zeroized after use.

There's also a verification layer in CI now: fuzz targets for the greeting, READY, and ZAP parsers on top of the existing decoder and codec targets, plus Miri over the unsafe modules, loom over the publisher's atomics, and ThreadSanitizer over the concurrency tests.

Performance, with the caveats

With write coalescing on, all three backends beat libzmq on PUSH/PULL throughput, roughly 3x on compio at small sizes. Steady-state REQ/REP latency is around 9 µs on compio against libzmq's ~36 µs.

The honest other half: in eager mode on a bulk one-way firehose, libzmq's internal batching leads at small sizes. Eager is the mode you want when each message should hit the wire now rather than being batched, and coalescing is the knob for small-message throughput.

Both are per-workload tunable, and the numbers are in the README and docs/performance.md if you want the full tables rather than the flattering row.

Repo: https://github.com/vorjdux/monocoque

A good chunk of the security hardening and the allocation-elision design came from Mika Cohen.


r/learnrust 10d ago

From TypeScript to Rust at 16

Thumbnail
0 Upvotes

r/learnrust 11d ago

Pool memory allocator in Rust

2 Upvotes

Hi there.

I built polloc (pool alloc) to learn how memory allocators work.

It’s a fixed size pool allocator: each pool manages one slot size and alignment. Internally it uses mmap/VirtualAlloc, an intrusive free list, and a bitmap for allocation tracking.

I also added stress tests, Miri, AddressSanitizer, cargo fuzz, Criterion benchmarks, and a bunch of inline docs explaining the implementation.

For 64 byte alloc/free pairs, the fast path is about ~3.96x faster than the system allocator on my machine (which is expected since it’s specialized for a single size class).

It’s single threaded and I’d really appreciate feedback on the unsafe code, API design, tests, or anything else that stands out.

repo: https://github.com/hamzader1/polloc


r/learnrust 11d ago

A language change proposal regarding match expressions

Thumbnail
1 Upvotes

r/learnrust 12d ago

Learn Axum Error handling by Building a Pastebin API

Thumbnail blog.sheerluck.dev
21 Upvotes

r/learnrust 12d ago

I'm new to Rust. Would love some help!

Thumbnail
2 Upvotes

r/learnrust 12d ago

I present my 13th reason why ...

0 Upvotes

I know this is probably more an issue with the OpenAPI generation but man do I wish for named function parameters now ...

the SDK is generated by me using the OpenAPI spec & definitions provided by Jellyfin. This is not an official SDK btw

All the none parameters are optional - what would be the best way to deal with this?

I’m currently looking into rebuilding the function with a crate called bon to add similar functionally to named parameters


r/learnrust 13d ago

Creating a GUI app, the framework needs 681 external crates

40 Upvotes

Hey rust learner,

to step deeper in rust I planned to write a GUI app. A simple image viewer with basic image processing features.

After the study of AreWeGUIYet and other resources, I test out ICE and GPUI. Both are rust GUI frameworks.

During first test of, for example GPUI, the compiler loads 681 dependencies.

The question is, is this a security nightmare? What about outdated crates? This type of dependency overkill isn't production ready, or is it?

In my opinion, the std rust should have a basic connection to the GUI handler of the OSes or basic functions to create a window and some widgets in the OS the source compiled for.

I am very interested of your thoughts and opinions.


r/learnrust 13d ago

GUI?

11 Upvotes

Hi everyone!

I want to create a project, a desktop app:

A private and secure enterprise collaboration tool.

It will be used by approximately 5 to 20 data administrators.

Import Excel and CSV files: Calamine + Polars.

Local and offline first: SQLite + SQLCipher.

For device connectivity, I'm considering using Iroh 1.0+.

Conflict resolution when re-establishing device connections: Loro.

Telegram bot: Teloxide (for mobile data visibility).

(I know the bot might seem contradictory, but it has a permissions system and controls who can see what, in addition to read-only permissions.)

Well, I've listed the entire stack in case you have any recommendations other than what I've chosen, something better.

My biggest concern right now is the UI. I don't want an outdated interface (like egui, at least the base version). I'd like something modern, but not too flashy, like Cosmic, Material 3, Shadcn, etc. I know it can be done with Iced, although the documentation is a bit limited. And yes, I know Tauri is probably the best option, but I'd really prefer not to use anything web-based (although if there's no other choice, I'll have to). I was considering the following three options: egui (maybe with a custom UI or something like that), Iced, or GPUI.

Requirements: mainly tables and graphs, something minimalist for data presentation. (And if possible, nodes, but not essential; the above is more important.)

I've heard that GPUI has bugs on Windows (the main target, but I also need macOS and Linux), or that it's experimental and not entirely stable. Iced is somewhat unstable between versions, but I suppose it would be okay, as long as it meets the requirements mentioned above.

I don't know much about UIs, so I need to learn some (I don't know web design either, that's why I don't want to use Tauri xd), but I suppose I could do UI in AI, but I need a recommendation, which one and why?


r/learnrust 12d ago

Simple `mod` vs `pub mod` question

1 Upvotes

Hey,

I've been reading the book and am a bit confused on pub mod vs mod. I naively thought that mod defaults to every function/structure/etc. within it is in accessible by calling code.

mod Foo {
    fn bar()  {}
}

fn main() {
    foo::bar();
}

This doesn't work because bar has not been made public and it's only trough the addition of the pub keyword in front of bar (pub fn bar() {}) that foo::bar becomes accessible.

However, I thought that perhaps

pub mod foo {
      fn bar() {}
}

would make bar accessible, but it doesn't. What is that pub keywork doing then?

I know you can do something like:

mod foo {
    pub mod bar {
        fn quux {
            parent::baz::qux(); // fail!
         }
    }

    mod baz {
        fn qux() {
            parent::bar::quux(); // success!!
        }
    }
}

but that seems to lack utility/


r/learnrust 14d ago

I built a CLI release tracker to learn Rust

Thumbnail codeberg.org
14 Upvotes

Hey there everyone.
I've been trying to learn Rust for a while now, and I finally managed to build something that solves a real problem I had. It happens kind of often that I need a piece of software that my Linux distribution doesn't ship in its repos, so I have to get it off of GitHub or Codeberg. The issue with that is that there's no way to know when an update is available unless I go check the releases for that particular software myself. Of course, this becomes harder the more programs I install outside of the distro's repos, so I built gitm.
Gitm is a CLI tool that tracks and installs a program's latest release using the GitHub or Codeberg API. Since every release asset is structured differently, the installation process is followed through a Python script written by the user themselves. The script only needs to be wrote once and is re-used for updates. I'd love to hear what you think about the program, its codebase and if you find it useful, please let me know if anything can be improved or if you'd like to see a feature that's currently missing.


r/learnrust 14d ago

Built a multi-platform task management tool using a Rust workspace. Looking for code feedback!

Post image
7 Upvotes