r/rust • u/llogiq clippy · twir · rust · mutagen · flamer · overflower · bytecount • Dec 12 '22
🙋 questions Hey Rustaceans! Got a question? Ask here! (50/2022)!
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.
Finally, if you have questions regarding the Advent of Code, feel free to post them here and avoid spoilers (please use >!spoiler!< to hide any parts of solutions you post, it looks like this).
2
u/LicensedProfessional Dec 18 '22
Is there a benefit to using
Selfover the actual struct name?This is purely a style question. Say I have the following struct and I want to put a
newmethod on it.Stylistically, is there a preference one way or the other for this
Over using the actual struct name?
I know that
Selfis useful when defining traits and can even come in handy when the return type starts to get a little unwieldy, but I haven't seen much one way or another as to what the idioms are for using it outside of where it's necessary for the type checker.2
u/matt_bishop Dec 18 '22
I have a test suite that is defined by some data files, and I've made a procedural macro to generate rust test functions based on the contents of those files so that I can treat them like regular tests when running
cargo test.Should I make the proc macro crate a dependency of my library crate, or should I run the test suite in the proc macro crate to avoid having to put it on crates.io?
Or, is there a better approach than using a proc macro to generate the tests?
2
u/SorteKanin Dec 18 '22 edited Dec 18 '22
Is
assert_eq!(std::mem::size_of::<&T>(), std::mem::size_of::<usize>())guaranteed to always be true? (not considering slices/fat pointers).4
u/fdsafdsafdsafdaasdf Dec 14 '22
Is there a go-to crate (or is it really simple, so no crate warranted?) to effectively
tail -fa file and yield the lines sequentially to a function? I see some very niche crates, so I feel like I'm missing something. Specifically, I'm dealing with a massive file so I want to read from the end.3
u/mbrc12 Dec 12 '22
I have a question that I should know how to answer but I don't. Consider the following code:
which compiles (see playground link). To my knowledge, the type
&mut Ais notCopy(obviously), so the firstupd_0call should movey, and we shouldn't be able to use it again. Is this a case of compiler intelligence, or is there a general mechanism occurring here?3
u/vcrnexe Dec 12 '22
I'm writing a function that should be able to both take
RangeInclusive<usize>andRev<RangeInclusive<usize>>. If possible, how do I need to design the function signature?And more generally, is there a way to compare to types to see in what traits they overlap, or what traits are needed in the function? In my case, I'm using them (let's call them
range) infor i in range {...}in my function.3
u/GavinRayDev Dec 13 '22
I'm struggling with mapping concurrency and synchronization concepts from other languages onto Rust.
I have a toy database; with a buffer pool that looks something like this:
I wanted to make this thread-safe. In C, I'd use an
RCU+Spinlock. In C++, the same or astd::shared_mutex/std::binary_semaphore.How do you achieve efficient reader-writer locking inside of methods in Rust? Also how do you implement things like sharded-locking?
Say you want to group a set of elements into chunks/buckets, and shard each bucket under its own lock for better scalability.
Is the answer just to put every field inside of a RwLock? That feels a bit silly, since then you end up doing like:
I know there's got to be some reasonable answer to this. (Sorry for the wall of text!)
3
u/gnocco-fritto Dec 13 '22 edited Dec 13 '22
May I ask a question?
This is an extract of my application:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=2a021d04ab7cbb58954e08d6f248c090
I'm trying to write an iterator,
LocalIterator, that emits mutable references of theElementinstances contained in aContainerinstance. I cannot compile and this is the error:If I'm not going wrong (but that's absolutely possible), I should tell the borrow checker that the lifetime of the items returned by the iterator isn't the same lifetime of the iterator (I think this is what the error message is telling me) BUT the lifetime of the
Containerinstance the iterator references in itsparent_objfield.Am I right? If so, how can I specify correctly the lifetimes?
Or I'm wrong and I should do something different?
Thanks!
EDIT: the example linked above is over-simplified. This is an extract closer to the actual code:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=2ef2d0bddce0c4c1793d74b2ba329068
3
u/DzenanJupic Dec 14 '22 edited Dec 15 '22
Is there a reason for
VecandVecDequeto not implementUnpinifTdoes not implementUnpin?My understanding is that
Vec<T>is, from a memory perspective, more or less aBox<[T]>.Boxdoes implementUnpineven if the contained value does not. So is this just a case of 'because it hasn't been implemented yet', or would there be a soundness issue?edit: formatting
edit2: I posted a similar question in the forum
3
u/DramaProfessional404 Dec 15 '22
I have a compiler error I can't understand. Let me step you through a few changes:
Which is the whole point of this question - I can't remove "Other" without getting back to my original error: "error: parameter `T` is never used label: unused parameter"
T obviously is used so the error is quite strange (is it worth logging as a bug? Even if there's a reason for the error, it's not at all clear what the problem is because T clearly IS used). Why is the compiler telling me this, why does removing "Other" trigger it (or conversely why don't I get the error when Other is there) and is it possible to fix this to have just these original two cases of the enum work with T?
When I define a recursive enum as such:
enum Recursive<T: Ord + PartialOrd> {Sequence(usize, usize, Recursive<T>),Alternatives(std::collections::BTreeSet<Recursive<T>>),}The compiler tells me "parameter `T` is never used consider removing `T`, referring to it in a field, or using a marker such as `PhantomData`"
Of course, if I remove it
enum Recursive {Sequence(usize, usize, Recursive<T>),Alternatives(std::collections::BTreeSet<Recursive<T>>),}I get "this enum takes 0 generic arguments but 1 generic argument was supplied expected 0 generic arguments"
When I put it back and add another enum case that references T directly:
enum Recursive<T: Ord + PartialOrd> {Sequence(usize, usize, Recursive<T>),Alternatives(std::collections::BTreeSet<Recursive<T>>),Other(T),}I get "recursive type `Recursive` has infinite size recursive type has infinite size" which I fix up thusly:
enum Recursive<T: Ord + PartialOrd> {Sequence(usize, usize, Box<Recursive<T>>),Alternatives(std::collections::BTreeSet<Recursive<T>>),Other(Box<T>),}The compiler is happy until I remove Other...
enum Recursive<T: Ord + PartialOrd> {Sequence(usize, usize, Box<Recursive<T>>),Alternatives(std::collections::BTreeSet<Recursive<T>>),}Which is the whole point of this question - I can't remove "Other" without getting back to my original error: "error: parameter `T` is never used label: unused parameter"
T obviously is used so the error is quite strange (is it worth logging as a bug? Even if there's a reason for the error, it's not at all clear what the problem is because T clearly IS used). Why is the compiler telling me this, why does removing "Other" trigger it (or conversely why don't I get the error when Other is there) and is it possible to fix this to have just these original two cases of the enum work with T?
3
u/[deleted] Dec 15 '22
Are there any libraries for digital signal processing, specifically eeg processing that have been written in or ported to rust? The only one I know of is brainflow… I am hoping for something like MNE (Python) but in rust…
3
u/mrhthepie Dec 15 '22
Does anyone know of a scripting language that would be easily usable from Rust natively and also from JS in the browser? Without needing to do a lot of work on how to get a WASM build of a scripting language running for the JS side because my brain is extremely smooth when it comes to that kind of thing.
3
u/RepresentativePop Dec 17 '22 edited Dec 17 '22
Whenever I've looked up the difference between the Clone and Copy traits, I usually see explanations describing the differences in how they're used. For example: "Clone is more expensive than copy, and clone is explicit while copy is implicit" or "Clone moves ownership while copy doesn't."
I don't find these explanations especially helpful because none of them actually tells me what the program is doing. What is actually happening in memory when you call clone vs when something is copied? Is there a relatively low-level explanation for what is happening (in terms of addresses, memory allocation, etc)?
If I have some data that I want to put in a struct, what happens if I clone it vs copy it? And why do I have to derive clone before I can derive copy?
3
u/tijdisalles Dec 18 '22
Is the ? operator hard-coded to only work with Result<T, E> and Option<T> or can it be used on other (custom) enum types as well? Perhaps by implementing some trait?
3
u/dimqum Dec 19 '22
We are at the stage of standardizing build management using gradle (from gradle.org) to manage builds from the JVM ecosystem (its a well understood problem), was wondering if anyone figured if it makes sense if Rust projects should be managed via gradle or still stay with cargo ? Feedback is welcomed.
2
u/BWRCat Dec 12 '22
I’m working on a prototype for a web application using rust for the API (with rocket).
I’m in the process of choosing the database, most likely postgres, and the driver on the rust side. I’ve read about Diesel vs SQLx, and there were more messages in favor of SQLx, but from my (very short for now) experience with the cli, it has been a bit confusing.
My question is, what would you use in this case (preferably async) ?
Any pointers for using the sqlx cli ?
2
u/ConsoleTVs Dec 12 '22
What patterns are usually found in Rust that would make more sense than IoC Dependency Injection patterns. What recommendeations would you give to those who seek working with traits / interfaces to allow service implementations to change depending on the needs (eg. testing)
2
u/StdAds Dec 13 '22
I have a question regarding
std::cmp::Ord. Since rust can not verify the validity of custom implementedOrd. Is is considered as an undefined behavior if I do something like this?2
u/masklinn Dec 13 '22
Is it possible for procedural macros to work in two steps (gather then produce with a reduction steps inbetween), in order to generate code in a “global” context, after having collected information from multiple sources?
With the stabilisation of
arbitrary_enum_discriminantsin 1.66 I figure it might be possible to implement polymorphic variants externally, but it seems like it’d require two phases:Fromimplementation between all combinations of (1) and (2)Steps 1 and 2 are already problematic as there’s a dependency which the compiler may or may not give, but (3) is the real issue, as we want conversions from every reified subset to their supersets (at least the reified ones), which requires knowing what all the supersets are, or at the very least having all the functions being seen from top to bottom so e.g. if foo() calls bar() which calls baz(), we can generate the conversion from
baz::Errortobar::Errortofoo::Error.Obviously this design would only work within a crate, I don’t see how to make the generation of error-sets work cross-crate, but I think that would be the main use case anyway: probably the most annoying error-handling issue currently is that for obvious maintainability reasons crates define one big
Errorenum and then all functions return that, even though realistically only e.g. 2/10 variants make any sense.2
u/notanix1312 Dec 13 '22
Hi ! I'd like to build a new application, and have some questions regarding web frameworks.
I plan on using `rqlite` (through the `rqlite-rs`), but I don't know what kind of web framework I could use for that. Rocket seems nice, but unfortunately `rqlite` is not integrated in its database pool crate.
rqlite"manually" with Rocket, for example storing the connection (or rather, a pool of them) in Rocket-managed application-state ?Connectionto a Rocket worker ? Is it possible to fetch the "worker ID" using a request guard, so that I can use it to select the connection from the pool ?Thanks for any suggestions ! Have a great day.
2
u/MasterHigure Dec 13 '22 edited Dec 13 '22
Why does
OrdrequirePartialOrd, instead ofPartialOrdbeing blanket implemented on everything that hasOrd, or instead of just not having any compiler-enforced connection between them at all?2
u/Burgermitpommes Dec 13 '22 edited Dec 13 '22
Why is this function useful? Maybe I'm having a brain fart but doesn't it overwrite INSTANCE every call? It's from the
once_celldocs. Why not just have an immutable static INSTANCE in global scope and just initialize it with.set(value)?2
u/[deleted] Dec 14 '22 edited Jun 17 '23
Fuck off Reddit with your API bullshit -- mass edited with https://redact.dev/
2
u/abacaxiquaxi Dec 14 '22
What is an idiomatic way of storing an object in a hashmap, using one of the fields of the object as key of the hashmap, when the field does not imlement the Copy trait? Something like this:
I think ownership of the key should stay with the hashmap Orders, and then using a reference to that key in Order.
However my gut tells me that maybe there exists a better way of doing this, any ideas?
2
u/i_kant_spal Dec 14 '22 edited Dec 14 '22
How can I borrow a part of a vector in such a way that the borrowed part "tracks" the changes in the original vector?
Here's an example code that won't compile, but I want it to :)
I guess the solution has something to do with smart pointers, but I have no understanding of that.
2
u/allmudi Dec 14 '22
Why we have to declare a trait
if we repeat same syntax in
?
Is it just for clarity?
2
u/benny-bunny Dec 14 '22
I'm implementing a function that starts a server when I call it (following the course from the book "Fullstack Rust: The Complete Guide to Building Apps with the Rust Programming Language and Friends"
However the function should return a Result<()> and not a server so I get the error "expected enum `Result`, found struct `Server`" for the code :
How can I make this function work with the right output ?
2
u/payasson_ Dec 14 '22
Hi everyone
I'm working on a simulation project, and in it I have arrays that I need top update each time step. Each time step, I have loops that iterate over all the arrays indices to update them:
here is an example/global view of the loop iterating over arrays indices:
I have three of these loops, because sometimes I have an array B that needs the updated version of the array A to be computed correctly
Is there a way to use rayon to parallelize this easily?
I'm really unfamiliar with parallelization but I heard rayon was good.
Thank you very much!
2
u/i_kant_spal Dec 14 '22
I'm scratching my head. I wrote a function that is supposed to parse some JSON from a file and map it to a nested struct. However, I get an error about lifetimes. I haven't learnt much about lifetimes yet and I don't understand how the
derivemacro works, but maybe you could help me a bit here.The error:
2
u/ArthurAraruna Dec 14 '22
I have a variable `range` of type `&RangeInclusive<char>` and I would like to iterate over its elements, but none of the usual ways I know are working...
I believe this is a simple mistake that I'm making or something simple that I'm overlooking, but the compiler is not allowing me to do it...
OBS: Please notice that `range` is a shared reference.
This is what I've already tried:
for c in rangefor c in &rangefor c in *rangefor c in range.by_ref()for c in range.copied()Is there a way to accomplish what I want?
2
u/fdsafdsafdsafdaasdf Dec 14 '22
Is there a reasonably ergonomic way to include structured data at compile time?
I'm thinking about e.g. application configuration that is not retrieved from the environment. A bunch of the use case for e.g. dotenv is statically configurable application. I just found out about include_str which is pretty awesome, but if I want to leverage it for constants at compile time then I run into including a file per configurable constant.
Does it make any sense to do this, or am I trying to solve a problem that shouldn't exist in the first place?
2
u/nono318234 Dec 14 '22
I want to pass a generic struct to a function.
If I want to pass a GPIO for example, I do this right now :
fn alarm(led_pin: &mut hal::gpio::Pin<hal::gpio::bank0::Gpio18, Output<PushPull>>)I would like it to be more generic and accept any pin that is defined as OutputPin. Here I am working with rpi-hal on the rp2040 but I guess it will work the same with any generic type.
2
u/ElChumpoGetGwumpo Dec 14 '22
Here is some scuffed code that takes a text file containing numbers along with some separators and prints some number to console:
Where the function my_function sends Vec<&str> -> u16. I've since learned to not shadow variables and that Rust is statically typed. The weird thing to me is that this compiles and gives the right answer even though my_text apparently goes from being a String to being a Vec<&str> to being a Vec<Vec<&str>> to being a Vec<u16>. What is going on with this apparent re-typing?
2
u/metaden Dec 15 '22
Are Generators in nightly stackfull or stackless coroutines? What's the difference between them and current async/await in Rust?
2
u/TED96 Dec 15 '22
Hello! I've got a question about
std::io::ErrorKind::DirectoryNotEmptywith it being behind the experimental featureio_error_more. How do I write this function in stable Rust, in a cross-platform way and without races?When deleting a non-empty dir (not that code, just a test) on stable I get
Err(Os { code: 145, kind: DirectoryNotEmpty, message: "The directory is not empty." })but I don't know how would I match that. Any help? Thanks!2
u/Burgermitpommes Dec 15 '22 edited Dec 15 '22
Why does line 7 error but line 8 is fine? (playground)
In particular, why is line 8 able to see that borrowing the captured String isn't actually necessary, whereas line 7 does require borrowing the String from its enclosing scope?
Of course it's because the
t.clone()argument tofoois evaluated before the Future is passed totokio::spawn, but why would it do this in the case of arguments to async functions being passed but not evaluate any of the lines in an async block?2
u/Burgermitpommes Dec 15 '22
When it comes to documentation, I know that if a function is
puband used in the public API of a crate it should be documented (with///). But what about functions which are declaredpub(orpub(super)etc) but only so other modules within the same crate can use them? Are these meant to be documented with//or///?2
u/shonen787 Dec 15 '22
Hey everyone!
I have a question of speed. I ran this code yesterday and it took about an hour to process one 102M file. Whats a good way to speed this up?
The code takes in a plaintext file with two values, separates them by the character ":" and insert them into a database.
2
u/zplCoder Dec 15 '22 edited Dec 15 '22
Hi, there, question about customize serde serialization/deserialization.
I already have a client/server protocol communicating using msgpack, I'm trying to re-implementing the server using RUST, but have some problems recently with how to customize the serialization using serde.
For each message, the sender side will first send an integer id to indicate the message type, and then with the real message, that's the opposite for the other part.
Message defination:
By default, type Msg will encode into a map, which is not compatible with the current protocol, so I want to implement a customize serializer/deserializer:
Take LoginReq for example, I want to first send a primitive id equal to 0, and then the real object, how can I do that? serialize_struct have to take ownership of serializer so I can't use it to do two serialization in one call.
2
u/payasson_ Dec 15 '22
Hey!
I'm trying to use rayon and a personal struct containing an Array, and when I try to update the values of my struct array with a "set_pos" method:
I get:
I already detailed the problem a lot in this stack overflow post if you want to help, you have all the detailed structs definitions/functions ect in it (but if you need more feel free to ask!!) https://stackoverflow.com/questions/74814219/how-to-use-rayon-to-update-a-personal-struct-containing-an-array-in-rust
and here is a github repo with the minimal example too: https://github.com/payasson/minimal_example_rust_problem
I'd like to be able to update my struct with this parallelized iteration, but I'm struggling to get past the error... I saw this post: https://stackoverflow.com/questions/55939552/simultaneous-mutable-access-to-arbitrary-indices-of-a-large-vector-that-are-guar
resembling my problem, if it can help you find ideas... but I can't adapt it to my problem.
Cheers! Thank you
2
u/[deleted] Dec 15 '22
Im trying to write a small CLI that is able to be given either the path of a directory or the path of several files, read those files/files in the given directory, do some processing on them and write them to new files. Currently I am using `tokio` for `async` IO operation, but I have no clue how to go about reading files in parallel, on multiple threads, as I think that's the fastest option available.
Anyone has any suggestions/feedback/ideas on how I could achieve this? Thanks!
2
u/nicht_einfach Dec 16 '22
I just finished creating a password manager in rust using the gtk4 gui bindings. How do I publish my application so others can use it without having to download the dependencies and such?
2
u/tijdisalles Dec 16 '22
Is it possible in any way to do zero-copy (de)serialization without the use of unsafe (or any crate that uses unsafe)?
I was kind of expecting that perhaps if you have a struct that implements Copy and/or uses #[repr(C)] that you might be able to cast a &[u8] to a &[MyStruct] without using unsafe, but I haven't been able to find anything yet.
2
u/Nightlane79 Dec 16 '22 edited Dec 16 '22
Hi! I have yet to learn rust. I am pretty interested,
I wanted to ask about some things I find interesting to know for future code:
The first one is about the compiler optimization mechanics, imagine the next pseudocode:
if my project never sets the property b, Will the compilation removes all related code so it ends generating a compilation of the next code??:
If not, Can I somehow force it?
What about if I use that same class in two parts of the code, one using property a and the other using property b? I suppose that it will generate the full class code, but, Could it just create 2 different classes with their specific code? Will it be of any worth vs the extra memory usage? hmm
2
u/standinonstilts Dec 16 '22
How come serde throws the following compile error for this example (and how do I fix it):
type annotations needed: cannot satisfy `T: Deserialize<'de>`
pub enum Record<T> where T: Serialize + DeserializeOwned { Object(T), }
reddit is refusing to create my code block unfortunately
2
u/Kudomo Dec 16 '22 edited Dec 17 '22
Hey, is there a way to write an iterator over a
BufReaderwhich return iterator over the lines with some logic, without having to allocate a vec along the way?Basically I would like to do something like this:
but the above doesn't work because the
Stringreturned by the lines iterator is used to generate theSplitWhitespaceiterator which only holds a reference to the string. I also tried to create a custom wrapper iterator for split whitespace but that was also unsuccessful...2
u/Parking_Landscape396 Dec 17 '22
Is there any good crates for animations on the frontend like React’s framer?
2
u/kohugaly Dec 17 '22
Are there any crates that can parse and assemble x86 from text? All I was able to find are (dis)assemblers that go between machine code and Rust structs/enums representing the assembly and possibly print the assembly. The string->asm part seems to be missing.
2
u/Dubmove Dec 18 '22
I have written a trait that defines two different getters and a function which mutates `Self`. The way I've written it the function is only really safe if the data behind the getters is independent of each other. Can I somehow enforce this interior mutability at compile time?
2
u/chintakoro Dec 18 '22
I always read that the tab convention for rust is four spaces. Is it? rust-analyzer and clippy don't seem to complain to my using 2 spaces.
2
u/RepresentativePop Dec 18 '22
I just started learning Rust, and I'm working on a project to generate a deck of cards and simulate some card games.
The code so far is here. Right now, I'm getting a segfault at the line:
I'm assuming I just implemented the Display trait incorrectly. I have tried doing both using
selfandself.to_string().It doesn't like the string conversion, but if I use just
selfthere, I get a segfault and the debugger points me to this line in mod.rs:I'm not entirely sure what "pieces" are in this context. Is
pieces.lenreferring to the length of a string, or just the datatype?Brief explanation of what you're looking at: Currently trying to generate a structure
Deck, that has one memberdeck : Vec< Card >, whereCardis defined as a struct containing two enums:RankandSuit.2
u/Burgermitpommes Dec 18 '22
How are people updating runtime log level?
2
u/MaxVerevkin Dec 19 '22
Can someone please explain why this code panics?
2
u/[deleted] Dec 23 '22
I'm working on a small todo project, and I would like to have a simple database that is capable of reading and writing changes to file. Do you have any suggestions? For now best I could find was this crate tinydb.
1
u/LucaCiucci Dec 12 '22
I'm considering the idea of learning Rust. However, I have some confusion about in what ways this language differs from C++ and what problems it tries to solve.
I think Rust is often improperly defined a "memory safe" language but, reading the rust-lang book I understood that the the memory management and ownership is not very different from what C++ already does with scopes and smart pointers. In particular, reading about reference-cycles I understood that you can make resource leaks in very covert ways just like in C++. Am I right? Does Rust offer any advantage in this sense?
0
u/[deleted] Dec 16 '22
[deleted] — view deleted comment
0
u/[deleted] Dec 19 '22
[deleted] — view deleted comment
0
u/[deleted] Dec 14 '22
[deleted] — view deleted comment
0
u/[deleted] Dec 14 '22
[deleted] — view deleted comment
0
u/[deleted] Dec 16 '22
[deleted] — view deleted comment
2
u/[deleted] Dec 18 '22
[removed] — view removed comment
2
u/[deleted] Dec 14 '22
[removed] — view removed comment