Dangling parameter deluxe - how to search for the origin?
⚓ Rust 📅 2025-11-08 👤 surdeus 👁️ 6Hi all,
I can not get my head around this error:
--> src/collection.rs:223:32
|
222 | if r.exists() && r.is_dir() && let Ok(c) = Self::open(&r.to_path_buf()) {
| --------------- temporary value created here
223 | return Ok(c);
| ^^^^^ returns a value referencing data owned by the current function
I think I understood this explanation. I can not pass some reference from within some method to its caller for that's a dangling reference. Same is true for any value / parameter inside a method that gets passed on to other (inner) methods. That parameter still is local to the method an can not be returned.
I tried to get a reduced implementation of my own sources. The reduction looks like this and works well.
use std::path::PathBuf;
use std::path::Path;
struct Collection {
path: PathBuf,
}
impl Collection {
pub fn new(r: &Path) -> Result<Collection, String> {
if r.exists() && r.is_dir() && let Ok(c) = Self::open(&r.to_path_buf()) {
return Ok(c);
}
Ok(Collection { path: r.to_path_buf(), })
}
pub fn open(r: &PathBuf) -> Result<Collection, String> {
Ok(Collection { path: r.to_path_buf(), })
}
}
fn main() {
let _ = Collection::new(Path::new("."));
}
I have no idea why my source (line 222 above) does not compile. I think it's the open-method of mine. Looking at that method - what am I searching for? What causes line 222 to fail? I'm using plenty of clone within my open to create owned data that will not dangle. What else can I check for?
1 post - 1 participant
🏷️ Rust_feed