14
submitted 2 weeks ago by gomp@lemmy.ml to c/rust@lemmy.ml

(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
[-] BB_C@programming.dev -4 points 2 weeks 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

[-] kelvie@lemmy.ca 0 points 2 weeks ago

Oof, this brings back PTSD for a lot of us that have worked with developers like this ☝️

[-] slowcakes@programming.dev 1 points 6 days ago

Well, all developers give each other ptsd, never seen a clean code base in my career. They all turn to shit, because 90% developers don't care, because it will be someone else's problem later.

That said, yeah don't do weird custom code, where you have to keep context in your head to understand the code.

this post was submitted on 26 Sep 2024
14 points (100.0% liked)

Rust Programming

8093 readers
9 users here now

founded 5 years ago
MODERATORS