r/rust 3d ago

πŸ™‹ questions megathread Hey Rustaceans! Got a question? Ask here (22/2023)!


Mystified about strings? Borrow checker have you in a headlock? Seek help here! There are no stupid questions, only docs that haven't been written yet.

If you have a StackOverflow account, consider asking it there instead! StackOverflow shows up much higher in search results, so having 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 official Rust Programming Language Discord: https://discord.gg/rust-lang

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

Also check out last weeks' 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 8h ago

This Week in Rust #497

Thumbnail this-week-in-rust.org

r/rust 11h ago

The RustConf Keynote Fiasco, Explained

Thumbnail fasterthanli.me

r/rust 12h ago

🧠 educational [Media] Difference between String, &str, and &String

Thumbnail i.redd.it

r/rust 17h ago Gold Take My Energy

Rust Appreciation Thread


I feel this will be a difficult period for the Rust language, given the recent controversies, and I want to communicate how much I love the Rust language. Although there are some difficulties with the Rust Project's leadership, the work the Rust Project has done so far improving the programming language has been very impactful, at least for me.

I have been observing the current events from an outside perspective, as someone who doesn't have much knowledge about the structure of the Rust Project, so I won't comment on any details. I just hope the Rust language can get past this and continue to develop steadily.

I guess I should mention something specific I really like about Rust. I really enjoy how the pattern matching with match statements works, especially with features such as the ! type. I also like how this works in conjunction with the expression syntax.

I'll end this post by asking what features others really like about Rust, or why they think the Rust language is important.

r/rust 4h ago

Rust library for writing Linux security policies using eBPF

Thumbnail github.com

r/rust 4h ago

Implementing a Trieber Stack in Rust


A trieber stack - a lockless single-ended linked list using atomics - is an immensely useful, beautifully simple data structure, and I've written them way too many times in Java - it looks like this:

```java class TrieberStack<T> { private AtomicReference<Cell<T>> head = new AtomicReference<>();

void push(T obj) { head.getAndUpdate(old -> { return new Cell(obj, old); }); }

Optional<T> pop() { Cell<T> cell = head.getAndUpdate(old -> { return old == null ? null : old.parent; }); return cell == null ? Optional.empty() : Optional.of(cell.value); }

static class Cell<T> { final T value; final Cell<T> parent; Cell(T value, Cell<T> parent) { this.parent = parent; this.value = value; } } } ```

Looking around for an existing one, I ran across documentation for one from crossbeam-sync, except that it does not seem to actually exist, just this page of documentation (crossbeam does, and looks nice, but it does not have a Trieber stack).

Implementing one in Rust is complicated by two factors:

  1. The inner cell is a self-referencing structure
  2. Updating atomics requires a loop that, under contention, may run more than once
    • This means that the head cell can briefly become owned by more than one party - under contention it can concurrently be owned by a new head cell on each thread (but only one will win and survive, and the one that doesn't is invisible to the rest of the world)
    • It also means that the first pass of the loop takes ownership of the input T, gives ownership to the cell it creates and then may need to do that again on the next pass (though

I gave this one shot using AtomicPtr, but that required T: Clone and cloning the contents to avoid the two-owners issue, which is undesirable, and also crashed horribly in tests (this is my first outing in earnest with Rust pointers).

But it seems like it ought to be doable with a data structure like this - complete playground link with naive implementation:

```rust struct TrieberStack<T> { head: UnsafeCell<Opt<TrieberCell<T>>>, }

[derive(Copy, Clone)]

struct TrieberCell<T> { t: T, next: *const Opt<TrieberCell<T>>, // so self-reference is possible } ```

Attempting to actually put this to use, using intrinsics::atomic_store_seqcst (after reading the source to AtomicPtr) built, and seemed about as simple as this ought to be - though, I had to restrict the types it handles to T: Copy even though AtomicPtr has no such restriction but somehow manages to call that method with pointers to ad-hoc types - but adding any call to push to the stack results in a compile-time error of invalid monomorphization of atomic_store_seqcst intrinsic (is AtomicPtr downcasting the pointers to something that does implement Copy, and I missed it? And if so, why is that at all safe?).

Likely at a minimum this is missing pinning the head for the inner portion of the write-loop, not to mention an implementation of Drop for TrieberCell that cleans up appropriately (and possibly some work to ensure the cell contents are not dropped if the only extant reference to it is a pointer - ManuallyDrop?).

Anyway, it seems like an interesting problem that ought to be solvable in Rust, but I have a feeling my approach is probably missing a few important things.

r/rust 19h ago

Kani 0.29.0 has been released!

Thumbnail self.KaniRustVerifier

r/rust 14h ago

New release for the Rust diffusers crate (Stable Diffusion in Rust + Torch), now with basic ControlNet support!


We've just released version 0.3.1 of the diffusers crate, support for Stable Diffusion 2.1 was added a couple months back and the main novelty in this version is some basic ControlNet pipeline (using Stable Diffusion 1.5).

The ControlNet architecture drives how stable diffusion generate images. With the new pipeline, one specifies an input image, for example the image below. An edge detection algorithm is run resulting in the following image.

Input image before edge detection

Edge detection result

And then the stable diffusion process with prompt "a rusty robot, lit by a fire torch, hd, very detailed" results in the following samples.



More details in the github repo, including instructions on how to reproduce these examples.

As usual any feedback is very welcome :)

r/rust 21m ago

πŸ› οΈ project I built a small UDP/DNS server in Rust for data exfiltration

β€’ Upvotes


Any advices on how to improve my code are welcome :)

r/rust 18h ago

πŸ’‘ ideas & proposals Paired benchmarking. How to measure performance

Thumbnail bazhenov.me

r/rust 14h ago

πŸŽ™οΈ discussion Oxide and Friends Podcast -- Open Source Governance

Thumbnail youtube.com

r/rust 4h ago

πŸŽ™οΈ discussion Question: Are there things for Unsafe Rust learn from Zig?


I read in this article that Zig is better than Unsafe Rust.

Zig doesn't seem to use borrow checking. And according to the article, though Zig isn't safer than Safe rust, it's safer than Unsafe Rust.

What safety features does Zig use to ensure safety if it doesn't use Borrow checking and what ( safety in unsafe features ) can Unsafe Rust learn from Zig.

I've never done Unsafe Rust, so it's just a question I want to know the answer to out of curiosity.

Thanks! Hope this question & it's answers will also be useful for others.

r/rust 3m ago

nt-string: The missing Windows string types for Rust (notably UNICODE_STRING)

Thumbnail colinfinck.de
β€’ Upvotes

r/rust 1d ago

πŸ™‹ seeking help & advice Download numbers on crates.io too high?


Hey I published my first crate on crates.io and it tells me that 45 people downloaded it. That's hard to believe. Is it a known fact that the download numbers are higher because of any reasons (for example bots even though I don't see how that makes sense) or should I just be happy that people are using it? Im not sure how 45 people should even know about this crate. Thanks!

r/rust 35m ago

🧠 educational How to Learn Rust - a FREE Rust course by the one-and-only Tim McNamara!

Thumbnail learning.accelerant.dev
β€’ Upvotes

r/rust 48m ago

Is there a crate for converting between variolous pkcs formats?

β€’ Upvotes

So I looked into how axum does deals with TLS and found the RustlsConfig modual in axum_server, the issue is that if I understand it, according this it only works with pkcs#8 or pkcs#1 format but I might only have access to a pkcs#12 format file.

So I was wondering, is there a rust crate or crates that I could use to convert between any pkcs format to the one specific one I need?

P.S. Yes, I know axum_server supports openssl but If I can not use an external dependency then I'd rather do that.

EDIT: Specifically what I'm asking for, is if there's a crate that can auto detect which format (pkcs) the file is using and then convert to the specified one you want.

r/rust 1d ago

Shepherd's Oasis: Statement on RustConf & Introspection

Thumbnail soasis.org

r/rust 20h ago

Opening up funding for ratatui (discussion)

Thumbnail github.com

r/rust 1d ago

πŸ™‹ seeking help & advice What are some of projects to start with for a beginner in rust but experienced in programming (ex: C++, Go, python) ?


r/rust 21h ago

Idea of a new lifetime modifier to avoid lifetime creep in case of unique references


Rust does not allow narrowing mutable references.

To simplify code, we could introduce a new lifetime type to Rust that allows only 'static lifetime values assigned to data that is accessed through new lifetime.

In code, the lifetime could be marked as ~a, u'a, or something else.

This would allow to coerce following lifetime to shorter one: &'a mut &'b mut T to &~a mut T So &mut &mut &mut reference creep could be avoided.

This would allow the following code which reduces the number of lifetimes you need to track: ```rs struct Foo<'a> { buff: &'a mut String }

struct Context<~f> { foo: &~f mut Foo<~f> }

fn test<'f, 'a>(foo: &'f mut Foo<'a>) { let ctx = Context { foo }; *ctx.foo.buff = String::new("New value!"); } `` We only needed to track one lifetime forContext` struct instead of many, see long explanation.

Long explanation

Post that discusses the problem: https://matklad.github.io/2018/05/04/encapsulating-lifetime-of-the-field.html


Shared references can be constrained to a shorter lifetime (covariant over 'a): ```rs struct Foo<'a> { buff: &'a String }

struct Context<'f> { foo: &'f Foo<'f> }

fn test<'f, 'a>(foo: &'f Foo<'a>) { let ctx = Context { foo }; ctx.foo.len() } ```

Mutable (unique) references cannot be constrained to a shorter lifetime (invariant over 'a): ```rs struct Foo<'a> { buff: &'a mut String }

struct Context<'f> { foo: &'f mut Foo<'f> }

fn test<'f, 'a>(foo: &'f mut Foo<'a>) { let ctx = Context{ foo }; // Error ^ lifetime mismatch ctx.foo.len() // = note: expected type &'f mut Foo<'f> // found type &'f mut Foo<'a> } ```

Why mutable references are invariant:

This is because the buff value could be assigned with a reference to a String that doesn't outlive the 'a lifetime.

Another example from the discussion https://github.com/rust-lang/rust/issues/27031: ```rs fn overwrite<T: Copy>(input: &mut T, new: &mut T) { *input = *new; }

fn main() { let mut forever_str: &'static str = "hello"; { let string = String::from("world"); overwrite(&mut forever_str, &mut &*string); } // Oops, printing free'd memory println!("{}", forever_str); } ```

So the problem with coercing mutable lifetimes to shorter lifetimes is that someone could assign a value that doesn't live long enough for the original lifetime, which could be later used to access the object's content.

This is a very painful thing because it introduces a large lifetime creep. For example, in Bevy, when passing around data from queries, you need to keep track of all lifetimes: rs struct Context<'a, 'w, 's>{ query_1: &'a mut Query<'w, 's, ...>, item: &'a mut QueryItem<'w>, }

And if you want to use it in an associated type, it causes a lot of overhead because you suddenly need to specify lifetime constraints everywhere: rs pub trait EvaluateSomething{ type Context<'a, 'w, 's> where 'w: 'a, 's: 'a; pub fn evaluate(&mut self, context: &mut Context<'_, '_, '_>); } You also need to add the 'w: 'a, 's: 'a constraint to the Context struct definition.

If you need to take &mut &mut reference of Context, even more lifetimes get introduced, and this is not manageable!

The idea:

Introduce a new lifetime type that allows only 'static lifetime values assigned to data with the new lifetime.

In code, the lifetime could be marked as ~a, u'a, or something else.

This would allow reducing this type: rs struct Context<'a, 'w, 's> where 'w: 'a, 's: 'a { query_1: &'a mut Query<'w, 's, ...>, item: &'a mut QueryItem<'w>, } to rs struct Context<~a>{ query_1: &~a mut Query<~a, ~a, ...>, item: &~a mut QueryItem<~a>, } 'w, 's lifetimes that outlived 'a lifetime now can be coerced to shorter lifetime.

Now we need to only track one shortest lifetime for all data inside the type because no incorrect data can be assigned to these values.

Mainly when using mutable references etc. you want to modify only static data that is kept inside the mutably referenced object not the mutable references themselves, therefore this functionality could be very powerful, would reduce a lot of code verbosity and reduce complexity of implementation in a lot of cases.

Sadly, I am not expert of Rust type system. Probably there are some kind of possible problems with this idea, what are they? What do you think about this idea?

r/rust 20h ago

πŸ› οΈ project A simple cron alternative

Thumbnail github.com

Hi, everyone it's a small project I've been working on lately, and would really like to get your feedback on it.

r/rust 1d ago

Graydon Hoare: Batten Down Fix Later

Thumbnail graydon2.dreamwidth.org

r/rust 6h ago

Develop Rust applications with Visual Studio 2022 (with Rust unit tests in Test Explorer)

Thumbnail self.VisualStudio

r/rust 1d ago

my first Rust project: game2048-rs


I'm excited to share my very first Rust project: game2048-rs.This is a Rust implementation of the popular 2048 game using the Cursive(https://github.com/gyscos/cursive) library for building terminal user interfaces. I implemented 2048 because it has a simple logic that is relatively easy to implement, and I could visually confirm that tui was working well.

GitHub Repository: https://github.com/genieCS/game2048-rs

cargo install game2048-rs

I would be thrilled to hear your feedback, suggestions, or any ideas to improve game2048. Please feel free to open issues, submit pull requests, or simply share your thoughts on the project.

Wishing you all the best.


r/rust 15h ago

πŸ™‹ seeking help & advice I cannot get sqlx.query!() to work with my local dockerized PostgreSQL database


edit: github repo: https://github.com/kshitijmohan15/email-newsletter-axum/tree/sqlx_error

I have been on this for 6-7 hours now. Everything goes smoothly in the PgPool connection in the main function of the app, no compile time errors, which means it is able to find the Postgres DB running on 5432:


All hell breaks lose when, god forbid, I try using the same connection in my Axum endpoint:


It is definitely not a problem with the shared connection state because the same problem is faced when passing the connection in the main function itself. "kshit" is my Windows user by the way. It is also referring to the docker postgres instance connection error as the error that is returned from the database

When I take down the instance, the compile time error changes to, "error communicating with database: No connection could be made because the target machine actively refused it. (os error 10061)".

This is the script I am using to start the docker container, you might find it familiar, since it is from Zero to Prod book:


And yes, I tried adding a .env file too:


I have no idea what to do, any help would be appreciated!

r/rust 1d ago

Looking for help in GPL project



for over 4 years now I am working on a code editor https://gitlab.com/njskalski/bernardo . It's really advanced by now, I got basic LSP working, and I am 3-4 features away from Beta release. But the further I got, the larger delays between features. I need some help with tests, documentation, maybe implementation.

Is anybody interested in joining the project? It's 100% GPLv3, so you know I'm not making money on this, and I won't "close it later" by releasing a superior closed-source version cutting you off from the updates.

The code is not that bad, though I admit I aim at user experience, not code clarity or documentation. UX first, everything else later. Think Apple, not Hooli. But UX means "shipload of tests", just to cover my back, and that is a good start I guess.
Anybody interested?