Hey there! I'm brand new to Rust and trying to read a directory of Markdown files. From there, I want to get the first line (among other things.)
I think I want a struct for this, since I'll want to perform several operations on the files. I've managed to get this code pieced together. I think it sounds reasonable, but it doesn't compile due to some lifetime errors.
pub struct Zettel<'a> {
path: &'a Path,
}
pub fn in_dir(directory: &Path) -> Result<Vec<Zettel>> {
let mut out = Vec::new();
for entry in fs::read_dir(directory)? {
out.push(Zettel {
path: &entry?.path(),
})
}
Ok(out)
}
Specifically, the compiler gives me this error:
error[E0515]: cannot return value referencing temporary value
--> src/lib.rs:22:5
|
18 | path: &entry?.path(),
| ------------- temporary value created here
...
22 | Ok(out)
| ^^^^^^^ returns a value referencing data owned by the current function
That seems reasonable to me (it goes out of scope after each iteration of the loop, right? And gets destroyed then?), but I'm not sure what I can do that will make this work!
I've already tried a bunch of things on &entry?.path()
: to_owned()
, clone()
, etc. I've also tried rewriting it in the to_iter/map/collect style and get the same error.
What's going on here? Surely this is just a gap in my knowledge!