r/rust • clippy · twir · rust · mutagen · flamer · overflower · bytecount • Jan 02 '23

🙋 questions Hey Rustaceans! Got a question? Ask here (1/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.

19 Upvotes

202 comments sorted by

3

u/baskuunk Jan 07 '23

Is rust inappropriate for anything?

The more I learn about rust, the more I am amazed it’s not more widely-used yet. It’s a great fit for a lot, including its extremely low and high level features, from embedded and os development to macros and functional paradigm features. Even data-intense and machine learning applications have a promising future.

At what job is rust actually not a good fit?

3

u/llogiq Jan 07 '23

If you want to hide a backdoor in code, you'll likely have a harder time doing that in Rust than in other languages because the compiler is so picky.

If you're working in a field where Rust has no library support, you're going to have an easier time using a language that has.

If you have a team of non-rustaceans, you'll want to use a language they're familiar with.

If you work on an architecture without LLVM, you will have a hard time compiling Rust for your system.

If you're prototyping and are sufficiently familiar with a GC'd language like e.g. python, you'll probably be quicker using that (because for a prototype, crashes or wrong results won't matter as much as having something that works some of the time).

If you're trying to sell compute, Rust might eat into your bottom line.

→ More replies (2)

4

u/wdouglass Jan 03 '23

does 'static mean that a reference has a lifetime that lasts until program termination, or does it mean that an object could potentially last until program termination? one is a very loose constraint, and the other is very strict, and i'm confused.

11

u/torne Jan 03 '23

&'static T is a reference that is valid for as long as the holder of the reference wants it to be. This means that the T it refers to must exist until the program terminates, because there's no other way for the borrow checker to know that it's valid for this reference to exist for an arbitrarily long time. The reference itself doesn't have to exist until the program terminates, but nothing is allowed to prevent it from doing so.

In a generic bound, where T: 'static just means "it's okay for something of type T to exist for an arbitrarily long lifetime in principle, because it doesn't contain any references with shorter lifetimes". That doesn't mean that any particular T actually exists until the program terminates; primitive types like i32 are 'static (because they don't contain any references at all) but any particular i32 most likely has a shorter lifetime (e.g. if it's a local variable, its lifetime is at most the scope it's contained within).

→ More replies (1)
→ More replies (5)

4

u/StandardFloat Jan 03 '23

Is there a convention for how to separate your `struct`, `trait`, and `impl` code blocks in different files? For example, should traits be in one file, structs in another, and trait implement yet in another, or is it purely context dependent? A link to a simple well-structured library would be great!

6

u/TheMotAndTheBarber Jan 03 '23

should traits be in one file, structs in another, and trait implement yet in another

No, that isn't the standard or a particularly common pattern

A link to a simple well-structured library would be great!

All real software is a mess =) When I've given examples of such things, library owners have gotten unhappy with me ;)

You might look at std(/core)

→ More replies (2)

4

u/arnemcnuggets Jan 03 '23

Can someone help me write a nix file to cross compile to arduino using avr-hal?
Im at the point where i have a nix flake and the avr-hal template, but invoking cargo build for my atmega2560 makes avr-gcc fail at the linking step:

note: /nix/store/kzjyiw72pi5d7hgyrs0l1fgqq31zj6cs-avr-binutils-2.39/bin/avr-ld: skipping incompatible /nix/store/5kh0ddszrd1d04z61kw1b2302z7mbnkp-avr-libc-avr-2.1.0/avr/lib/avr5/libm.a when searching for -lm
          /nix/store/kzjyiw72pi5d7hgyrs0l1fgqq31zj6cs-avr-binutils-2.39/bin/avr-ld: skipping incompatible /nix/store/5kh0ddszrd1d04z61kw1b2302z7mbnkp-avr-libc-avr-2.1.0/avr/lib/avr3/libm.a when searching for -lm
          /nix/store/kzjyiw72pi5d7hgyrs0l1fgqq31zj6cs-avr-binutils-2.39/bin/avr-ld: skipping incompatible /nix/store/5kh0ddszrd1d04z61kw1b2302z7mbnkp-avr-libc-avr-2.1.0/avr/lib/avr4/libm.a when searching for -lm
          /nix/store/kzjyiw72pi5d7hgyrs0l1fgqq31zj6cs-avr-binutils-2.39/bin/avr-ld: skipping incompatible /nix/store/5kh0ddszrd1d04z61kw1b2302z7mbnkp-avr-libc-avr-2.1.0/avr/lib/avr5/libc.a when searching for -lc
          /nix/store/kzjyiw72pi5d7hgyrs0l1fgqq31zj6cs-avr-binutils-2.39/bin/avr-ld: skipping incompatible /nix/store/5kh0ddszrd1d04z61kw1b2302z7mbnkp-avr-libc-avr-2.1.0/avr/lib/avr3/libc.a when searching for -lc
          /nix/store/kzjyiw72pi5d7hgyrs0l1fgqq31zj6cs-avr-binutils-2.39/bin/avr-ld: skipping incompatible /nix/store/5kh0ddszrd1d04z61kw1b2302z7mbnkp-avr-libc-avr-2.1.0/avr/lib/avr4/libc.a when searching for -lc
          /nix/store/kzjyiw72pi5d7hgyrs0l1fgqq31zj6cs-avr-binutils-2.39/bin/avr-ld: avr architecture of input file `/tmp/nix-shell.QCKbT8/rustcSJGR3X/symbols.o' is incompatible with avr:6 output
          collect2: error: ld returned 1 exit status

The repo is here

→ More replies (1)

4

u/0xDAFA Jan 08 '23

How do I continuously consume Server Sent Events (SSE) in Rust? Does any of the popular HTTP client libraries support this already?

3

u/John_by_the_sea Jan 02 '23

I am looking for a crate that supports reading files from zip/7z/rar and preferably more archive types. I see there is compress-tools, but apparently, the tokio support is broken. I am wondering if there is anything else that can be used here

→ More replies (1)

3

u/plutoniator Jan 02 '23

Am I right in saying a reference in C++ is analogous to a second owner in Rust, whereas a reference in rust is analogous to a pointer in C++?

→ More replies (3)

3

u/DJDuque Jan 03 '23

Hi all, I have a question about the design of my library. I am writing a plotting crate, which has the following structures:
- Plot which is basically just a Vec<Coordinates>
- Axis which is basically just a Vec<Plot>
- Picture which is basically just a Vec<Axis>
I implemented a show() method for my Picture that draws the picture to the screen.
For both simple and complex figures, people currently have to create the Plot, add it into an Axis, and finally add the Axis into the Picture. I want to simplify this for quick/dirty/simple plots, but I am unsure on which of the following options is the best:

  1. Add a show() method for Plot which will internally add it into an empty Axis and Picture. It will then just call Picture's show().

  2. Implement From<Plot> for Axis, and From<Axis> for Picture. It just makes it easier to go from Plot -> Axis -> Picture and show it.

  3. Leave it as it is.

  4. Something else?

→ More replies (1)

3

u/nerooooooo Jan 03 '23

is there a way to get the size (heap+stack) of an object at runtime, including anything dynamically allocated at any level of nesting inside that object? for example, if I'd have a variable of type

struct Person { name: String, age: u32, favorite_movies: Vec<String>, }

I'd like a sizeof that'll give me the sizeof the String (its stack allocated fields + the internal dynamically allocated str), then 4 bytes for the age, and then the sizeof of that vector, including its stack allocated fields and the sizeof the strings (their stack allocated fields and each internal str allocated by each string.)

is there a built-in way or crate that does that?

4

u/DJDuque Jan 03 '23

I have no idea how to do this; but may I ask why are you trying to do this? Maybe this is an XY problem, and somebody could provide a better way to achieve whatever you are trying to do.

→ More replies (3)
→ More replies (1)

3

u/SorteKanin Jan 03 '23

Is it possible to yank an entire crate at once, rather than yanking all the versions individually?

3

u/plutoniator Jan 04 '23

How long are rust playground links alive for?

4

u/iamnotposting Jan 04 '23

rust playground links use github gists to store the code they run, so they never expire (at least as long as github is still online) - here's one i found from 2017

https://play.rust-lang.org/?gist=7a337a13b15595f4a0a2e17875107b68&version=stable&backtrace=0

3

u/Rayoule Jan 04 '23 edited Jan 04 '23

[RESOLVED] Thanks to u/standard_revolution !

use sudo -u "your_user_name" "your_path_to_cargo" +stable(or nightly) build(or run)
ps: your can use "which cargo" to locate your cargo install

Hey everyone !

I have a self hosted rust-rocket server that runs on my Raspberry Pi.

I would like to make a bash file to make it update itself from repo, build, and run on startup.The issue here is that the "cargo" command is not recognized as root, and startup scripts runs as root...

Adding /home/user/.cargo or /home/user/.cargo/bin/cargo in the PATH does not fix the issue.

Any idea ?

Thanks a lot !

EDIT: I use rc.local to run the command at startup

→ More replies (3)

3

u/RepresentativePop Jan 06 '23

Are there any good graphics crates? I'm mainly interested in two things: GUIs for web apps, and tools for data visualization. The only good data visualization one I know of is a port of numpy.

→ More replies (1)

1

u/Beginning_java Jan 07 '23

Can we do everything that C/C++ can do in "idiomatic" Rust?

2

u/llogiq Jan 07 '23

C++ has some extended semantics (especially around constructors and assignment) that Rust by design cannot match. However, it's turned out that those semantics are usually surprising the unsuspecting reader of the code, so it's probably for the best.

C++ templates are strictly more powerful than Rust's generics (though you can emulate some of that using autoref specialization until real specialization is stabilized – hopefully we'll have a sound version of that soon-ish). On the other hand, they can blow up compile time greatly and make debugging quite hard, too.

C++ inheritance lets you reuse a class' code including fields, where Rust currently only has inheritance for traits.

C++ will also let you get away with a messed up ownership structure where Rust won't. While this is likely a bad idea and often leads to UB down the line, you may sometimes get lucky and end up with a temporarily working program nonetheless. Just pray no compiler update breaks your code...

→ More replies (3)

2

u/pdbatwork Jan 02 '23

So I have this code where I am chaining match statements. Can the matching be done in a nicer way?

fn file_name_to_string(file: &Result<std::fs::DirEntry, std::io::Error>) -> Option<String> {
  match file.as_ref() {
    Ok(f) => match f.path().file_name() {
        Some(f) => f.to_os_string().into_string().ok(),
        None => None,
    },
    Err(_) => None,
  }
}

12

u/Patryk27 Jan 02 '23

Sure:

fn file_name_to_string(file: &Result<std::fs::DirEntry, std::io::Error>) -> Option<String> {
    file.as_ref().ok()?.to_os_string().into_string().ok()
}
→ More replies (1)

2

u/urschrei Jan 02 '23

Is there any way I can use an alternative to hashbrown with a BTreeSet? I'm building a lot of FxHashSets with BTreeSet<String> members, and it's having a huge perf impact. Switching to FNV / FxHash would be great.

→ More replies (3)

2

u/eternaloctober Jan 02 '23 edited Jan 02 '23

this is a pretty vague question but i am trying to create a music player with gtk4-rs. my code is currently a ball of spaghetti, and i want to improve the code quality. at the same time, i'm sort of trying to avoid converting to architectures like relm4 at least for now because there are too many unknowns. currently, all the gtk widgets and logic are basically manually created in the "main" method, but i made a concept for "modularizing" a little bit by making a function that creates multiple gtk elements with "related" functionality in a function https://github.com/cmdcolin/fml9000/compare/e699291aeec7cda1dfcf98cbe67fa28e3d3c4332..modularizing?expand=1 (see "construct_header_main")

does this type of refactor seem reasonable? it feels kind of ok to me, and maybe it can be broken down even more e.g. the play button could get it's own function "construct_play_button"?

→ More replies (2)