(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.

  • Sibbo@sopuli.xyz
    link
    fedilink
    arrow-up
    6
    ·
    2 months ago

    I think you already used a pretty nice way, which is using shadowing. If one variable is only used for the creation of another, simply shadowing it keeps your namespace clean.

    Sometimes it doesn’t make sense to give the shadowed variable the same name, because that name doesn’t describe its content very well. But in this case it seems like that is not a concern.