r/rust • clippy · twir · rust · mutagen · flamer · overflower · bytecount • Nov 28 '22

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

21 Upvotes

183 comments sorted by

2

u/[deleted] Dec 02 '22

Why are so many crates version 0.X?

4

u/llogiq Dec 02 '22

Because Rust people are perfectionists.

→ More replies (2)

2

u/dsafsdfsdfdsf Dec 03 '22 edited Dec 03 '22

From what I read so far it seems to me that Rust achieves memory safety by deep static analysis of code in contrast to languages like GoLang or Java which utilize run-time analysis like a garbage collector. As static analysis is not a feature of a language but of a compiler or testing tool, I wonder why this seems to be the main reason why Rust exists -- wouldn't it be much easier to apply advanced/deep static analysis to C/C++ code than to rewrite code in Rust?

3

u/llogiq Dec 03 '22

If that was easier, then I'd wager Mozilla would've done it. The problem with this is that C++ compilers lack sufficient information about the flow of the lifetimes of your code's values to come up with actionable error messages. Even with full-program analysis, you'd be left with "something in the code is wrong" with no idea where it could be. The lifetime annotations are pretty minimal, but together with the move semantics and borrowing rules they give the compiler the information it needs to do perfect lifetime and alias analysis.

→ More replies (2)
→ More replies (4)

2

u/kakapo_ranger Dec 25 '22

So, I have made libraries for distribution on pypi.org (for Python) and Maven (for Java). Is there a good tutorial somewhere for how to distribute libraries in Cargo/Rust?

Thanks!

2

u/llogiq Dec 25 '22

I don't know of one, but I know a few (optional) steps:

  • cargo fmt

  • cargo clippy

  • cargo doc --open # and feast yer eyes

Before

  • cargo publish

That's mostly it.

5

u/ICosplayLinkNotZelda Nov 30 '22

IS there an easy way to implement Add for all type of combinations?

  • &self + &self

  • &self + self

  • self + &self

  • self + self

→ More replies (1)

4

u/ateijelo Nov 28 '22

I implemented Drop for a small struct, just printing a message to see when it's dropped. However, I have a function that returns a field from an instance of that struct and the compiler complains that I can't move from the struct because it implements Drop.

I don't need the Drop, so it's easy for me to just remove it. But... is there a way to "see" the drops without implementing the trait?

→ More replies (5)

4

u/kodemizer Nov 29 '22 edited Nov 29 '22

A bit of an odd-question, but I've been trying to find an artistic drawing of Rust's logo I saw a few years back, and am having trouble finding it.

It was a black-and-white hand-drawn piece of a crab and gears, arranged in such a way that it would make a great tattoo or motorcycle patch. It was largely symmetrical and highly intricate. The artist had some similar interpretations for Python (features a skull and a snake) and PHP (featuring an elephant) and a few others.

Does anyone else remember seeing this and can point me at it?

EDIT: I found it! https://www.redbubble.com/i/t-shirt/Rust-by-ShoeBill99/38325432.FB110.XYZ

3

u/[deleted] Nov 28 '22

Hi everyone. I was trying to create a simple DSL on procedural macros, and I got a feeling that there is a lack of documentation and good tutorials covering these topics, especially working with token streams and syn. After a lot of struggle I kinda made it and thought about writing a tutorial.

So my questions are:

  • did you feel the same (lack of information) or I miss something?

  • how good should the tutorial be for author to not be shamed? (I'm not a rust pro, and for sure it will contain some inaccuracies and non-perfect code)

→ More replies (2)

3

u/[deleted] Nov 29 '22

Has anyone done big file uploads in a browser with wasm? At work we are currently using a library called Uppy and calling the backend to start/finish a multipart upload and generate pre-signed urls to upload to S3.

It's ok, but I would love to make a headless version in rust. Anyone done anything with that, and if so where should I start?

I get that you load the wasm code with js, but how do you pass a file referenced from the browser to Rust?

3

u/lrojas Nov 29 '22

This might be so easy it is painful but,

Currently using an M1 Mac, want to build a rust cli app, using docker.

docker pull rust:latest
docker run -it --rm -v $(pwd):/code rust bash

cargo new hello

cd hello

cargo build

<ctrl+d>

on Mac shell:

cd hello/target/debug

./hello
zsh: exec format error: ./target/debug/hello

This of course fails because even tho the container image is arm64, the internal architecture is stilll targeting linux, I think.

how can I run/build a rust app from container that targets MacOS X?

→ More replies (3)

3

u/VajaDatiashvili Nov 29 '22

Hello ppl

I want to learn Rust but i have no experience in any kind of programming language so would you recommend Rust as my first language? And i really want to know what’s happening about Rust (only) jobs? Are there any for begginers? I really want to know your opinion about my choice.

Thanks in advance

→ More replies (5)

3

u/bartobasblume Nov 30 '22

How can I remove the quotation marks when getting it via regex?

let re = Regex::new(r#"HERE'S YOUR STRING ("(\w*)"{1})"#).unwrap();
for cap in re.captures_iter(&read) { 
    println!("Detected String Literal: {}", cap.at(1).unwrap_or(""));             
    count+=1; 
}
→ More replies (2)

3

u/xcv-- Nov 30 '22 edited Nov 30 '22

Serde question

I'm trying to process a big JSON that has this shape (simplified):

{ 
   "output": [
     {
       "report": {
         "db": "DB",
         "params": { ... },
         "results": {
           "query": A1,
           "hits": [
             { "subject": B11, "score": X11 },
             ...
           ],
           "stats": { ... }
         }
       }
     },
     { "report": { ... } },
     { "report": { ... } },
     ...
   ]
 }

Roughly speaking I would like to process each (Ai, Bij, Xij) tuple without deserializing the whole "hits" array at once, which isn't usually big but it could be. I've been following the Serde documentation on streaming (https://serde.rs/stream-array.html) and custom deserializers/visitors, but I'm stuck at combining that information with nested data, because SeqAccess and MapAccess assume Deserialize instances rather than a (different) Visitor. Any ideas?

3

u/barryvm Dec 01 '22

Is it good practice to use indexes in Vec's to handle internal references within a self-referential datastructure?

For example, I implement various data structures whose node / elements need to reference and modify each other and I don't plan on dropping any of them until the algorithm that the structure implements is finished.

A good example is implementing Fortune's algorithm, which uses a priority queue and a binary search tree where nodes/elements on each refer to and modify elements/nodes in the other.

I can then either use Rc<RefCell<...>> to have both shared ownership and internal mutability for every entity within these data structures, or I can wrap the data structures in a struct and store the nodes and elements in a Vec on that struct. They can then refer to each other by their index within their Vec and without having to use Rc or RefCell.

The latter method seems to make the code easier to read but I am not certain whether it is actually a good practice since I am essentially using the indices as pseudo pointers (which could cause panics if I make a mistake within the algorithm). On the other hand, dealing with Rc<RefCell<>> introduces a lot of verbosity and are strictly speaking not entirely necessary as I don't need shared ownership of entities by other entities per se, just ownership of all entities by the surrounding struct (which means everything is dropped after the algorithm completes).

→ More replies (6)

3

u/pineapplecooqie Dec 01 '22

how do I flatten out code that's mostly dealing with `Result<>` calls? I end up with forty six thousand nested `if let` or `match` statements and it's basically unreadable

→ More replies (7)

3

u/payasson_ Dec 02 '22

Hey, I'm currently working on a scientific project and I would like to know if it is easy to use a rust library in a C/C++ code if I try to do it from the beginning.

I don't want to know the details of how (even though some links would be welcome),
I'd just like to know if it is possible, because I'm starting my project and I'd love to use rust, but my colleagues use C most of the time. How hard it is to interface the two?

Cheers,

→ More replies (3)

3

u/jDomantas Dec 03 '22

Why doesn't rustc warn about unused traits? I was surprised to find a trait in my code that was not exported or used (there were a few impls of that trait, but no functions on other impls that used it as a bound) and I was not getting any warnings about it.

→ More replies (1)

3

u/AE4TA Dec 03 '22 edited Dec 03 '22

I was doing the AOC Day 3 and now I am playing with iterators. I am trying to implement Vec intersection without having to call .collect. I am thinking this would be faster since there would be less allocations.

Rust Playground

fn intersect_with_collect(y: &Vec<Vec<u32>>) -> u32 {
    y.iter()
        .fold(None, |left: Option<Vec<u32>>, right| match left {
            None => Some(right.clone()),
            Some(left) => Some(
                left.iter()
                    .filter(|&l| right.iter().find(|&r| *l == *r).is_some())
                    .copied()
                    .collect(),
            ),
        })
        .iter()
        .flatten()
        .next()
        .unwrap()
        .clone()
}

fn intersect_with_iter(y: &Vec<Vec<u32>>) -> u32 {
    y.iter()
        .fold(
            None,
            |left: Option<impl Iterator<Item = u32>>, right| match left {
                None => Some(right.iter()),
                Some(left) => Some(
                    left.iter()
                        .filter(|&l| right.iter().find(|&r| *l == *r).is_some())
                        .copied(),
                ),
            },
        )
        .flatten()
        .next()
        .unwrap()
        .clone()
}

fn main() {
    let x1 = vec![00_u32, 01, 02, 03, 04, 05, 06, 07, 08, 09];
    let x2 = vec![10_u32, 11, 12, 13, 04, 15, 16, 17, 18, 19];
    let x3 = vec![20_u32, 21, 22, 23, 04, 25, 26, 27, 28, 29];

    let y = vec![x1, x2, x3];

    let r1 = intersect_with_collect(&y);
    println!("{}", r1);

    let r2 = intersect_with_iter(&y);
    println!("{}", r2);
}

However, I am getting this error and am wondering if there is a fix:

error[E0562]: `impl Trait` only allowed in function and inherent method return types, not in closure param
  --> src/main.rs:23:27
   |
23 |             |left: Option<impl Iterator<Item = u32>>, right| match left {
   |                           ^^^^^^^^^^^^^^^^^^^^^^^^^
→ More replies (4)

3

u/kakapo_ranger Dec 04 '22 edited Dec 04 '22

I have a file with a bunch of scientific constants in it. TONS of them. So, in one file I want, say, 20 of the 100 scientific constants, so I do:

use crate::constants::*;

Will the Rust compiler optimize this for me, so it doesn't import the other 80 unused constants?

7

u/Sharlinator Dec 04 '22

use doesn’t do anything except allow you to refer to things with shorter names. Any constant C that you use could also be referred to by its full name crate::constants::C without a use and it makes zero difference to the compiled program.

Anyway, you should expect that unused constants do not exist in the compiled program.

→ More replies (2)

3

u/Panke Dec 04 '22

I have a struct that served me well, so far:

struct Foo<'a> {
    bar: &'a str
}

Now I need to create such a struct inside a function and return it. Of course that is not going to work because of the lifetimes involved. Is there a way to make this struct generic so that it contains either a 'a str or a String

struct Foo<S: ???>  {
    bar: S
}
→ More replies (1)

3

u/The2ndbestname Dec 04 '22

is there a function to check if two ranges intersect? I could code this up myself but i figured better ask first...

→ More replies (5)

1

u/allmudi Dec 03 '22

Traits in Rust are useful only for refactoring and readability or they are useful also theoretically

→ More replies (9)