this post was submitted on 26 Sep 2024
0 points (NaN% liked)

Rust Programming

8118 readers
2 users here now

founded 5 years ago
MODERATORS
 

(I'm just starting off with rust, so please be patient)

Is there an idiomatic way of writing the following as a one-liner, somehow informing rustc that it should keep the PathBuf around?

// nevermind the fully-qualified names
// they are there to clarify the code
// (that's what I hope at least)

let dir: std::path::PathBuf = std::env::current_dir().unwrap();
let dir: &std::path::Path   = dir.as_path();

// this won't do:
// let dir = std::env::current_dir().unwrap().as_path();

I do understand why rust complains that "temporary value dropped while borrowed" (I mean, the message says it all), but, since I don't really need the PathBuf for anything else, I was wondering if there's an idiomatic to tell rust that it should extend its life until the end of the code block.

you are viewing a single comment's thread
view the rest of the comments
[โ€“] [email protected] 0 points 1 month ago (1 children)

I don't think you can, and I think it makes sense: it would be weird for the compiler to unexpectedly generate hidden variables for you.

For all the compiler knows, the temporary variable could hold a file handle, a database transaction, a Mutex, or other side effects in their Drop implementation that would make when it's dropped matter. Or it could just be a very large struct you might not expect to keep around until the end of the function (or even, the end of the program if that's a main loop).

So you should be aware of it, and thus you need the temporary variable like you did even if you just immediately shadow it. But at least you know you're holding on to it until the end of the function.

[โ€“] [email protected] 0 points 1 month ago

Yeah, it occasionally bothers me, too, that I have to pull out an assignment, but in terms of the mental model, I do think, it's absolutely vital to always have ownership associated with a concrete variable slot.