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

  • _hovi_@lemmy.world
    link
    fedilink
    arrow-up
    0
    ·
    1 month ago

    As someone else said I think the shadowing works well here.

    I do also wanna mention that depending on why you need this conversion, you could use impl AsRef<std::path::Path> for your function signature so it can accept &PathBuf or &Path. Then, just use that argument with e.g. p.as_ref() to get a &Path in the function body

  • BB_C@programming.dev
    link
    fedilink
    arrow-up
    0
    ·
    edit-2
    1 month ago

    There is a general mechanism in Rust that allows language users to add their own sugar. It’s called macros 😉

    macro_rules! keep {
        (let $id:ident = $expr:expr => $($tt:tt)+) => {
            let $id = $expr;
            let $id = $id$($tt)+;
        }
    }
    
    fn main() {
        keep!{ let path = std::env::current_dir().unwrap() => .as_path() };
        println!("{path:?}");
    }
    

    You can remove let from the macro’s fragment specifier and invocation.

    • Ephera@lemmy.ml
      link
      fedilink
      arrow-up
      0
      ·
      1 month ago

      While macros are cool and it’s good to keep them as an option in the back of the mind, it should be clarified that you’re not supposed to immediately reach for macros for small things you don’t quite like about the language.

      Excessive macro use makes it impossible for others (including your future self) to read your code and there’s often good reasons why it’s designed like it is.

      • BB_C@programming.dev
        link
        fedilink
        arrow-up
        0
        ·
        1 month ago

        you’re not supposed to immediately reach for macros

        correct

        for small things you don’t quite like about the language.

        incorrect

        Excessive macro use makes it impossible for others (including your future self) to read your code

        N/A. the macro above is trivial.

        impossible for others to read your code and there’s often good reasons why it’s designed like it is.

        fiction