#Why doesn’t this variable live long enough?
21 messages · Page 1 of 1 (latest)
You're redeclaring temp_string each iteration of the for loop. The declaration outside the loop has no effect. You already have a String, which is an owned value, so why not make path_vec a Vec<String>?
I’m trying to pass the &str into Command::new().arg(), but it can’t find the file despite it existing when I use a String
I don't follow. Can you provide code examples of what works and what doesn't?
I was under the impression that .arg() had to take a &str, but it turns out both ways return “No such file or directory”
When I test it with ls, it finds the file
If you want the data to be contained in the vector, (owned by the vector), it has to be a Vec<String>. You can then pass it to function that require &str through .as_str() as needed. By using &str, you're trying to reference strings contained somewhere else. But these values don't survive iterating through dir_read
Other remark, I've been taught that pushing to Vec inside for could be sub-optimal performance-wise because of memory reallocation. To build your Vec<String> optimally, you could instead use a map/collect flow:
let path_vec: Vec<String> = dir_read.into_iter().map(|dir_entry| dir_entry.as_ref().unwrap().path().into_os_string().into_string().unrwap()).collect()
You may also want later to replace the unwrap() calls with error management in a way that make sense to your program; for example, you could filter them out of path_vec, if it make sense. In general, unwrap is fine at prototype level but you want to avoid the program to panic on errors as it provides unfriendly traceback to users, and may crash functionality that might otherwise have been delivered.
just saying, ReadDir implementation doesn't have a known size at all, so it can't even preallocate for collect()'
So the code doesn't work ? Or more like it doesn't optimize ?
I meant that the for loop with push is as performant as collect in this case
usually you're right, collect can reserve some capacity for some iterators
I'm willing to bench it nonetheless, for curiosity / research purpose
sure, you can try that
I'm 99% sure that it's gonna be the same
or like the difference will come from other factors
yea likely bc there is an os list call in that, that is going to take most of the time hmmm

the point is that collect will just call push in a loop, without reserving capacity
so ultimately the behavior is exactly the same
ok, it's gonna reserve 4 elements lol
Yea i imagined that you could do something more clever when you batch the number of elements; but you still have to build them one by one and store them somewhere which is exactly what vec.push does... I did the bench nonetheless bc I procrastinate on my project plus I was a bit exercising myself on using the microbenches. Turns out they are exactly the same as predicted