#Why doesn’t this variable live long enough?

21 messages · Page 1 of 1 (latest)

gentle spade
#

My goal is to get a Vec<&str> of paths from read_dir() by looping over the ReadDir struct. My problem seems to be that temp_string (the path added each iteration) needs to live longer than the Vec referencing it, so I declared temp_string before the Vec in line 8, but it didn’t have any effect.

brisk canopy
gentle spade
brisk canopy
#

I don't follow. Can you provide code examples of what works and what doesn't?

gentle spade
#

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

atomic sentinel
#

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.

full vine
atomic sentinel
full vine
#

usually you're right, collect can reserve some capacity for some iterators

atomic sentinel
#

I'm willing to bench it nonetheless, for curiosity / research purpose

full vine
#

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

atomic sentinel
#

yea likely bc there is an os list call in that, that is going to take most of the time hmmm

full vine
#

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

atomic sentinel
# full vine so ultimately the behavior is exactly the same

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