Storing a PathBuf field, from a impl AsRef function parameter

⚓ Rust    📅 2025-06-19    👤 surdeus    👁️ 4      

surdeus

Warning

This post was published 55 days ago. The information described in this article may have changed.

Let's say I have a struct called App, and this struct has a constructor similar to:

use std::path::{Path, PathBuf};

pub struct App {
  file_path: PathBuf,
  // other fields
}

impl App {
  pub fn new(file_path: impl AsRef<Path>) -> Self {
    // do some work with the path, such as opening with std::fs::File::open(..) and 
    // deserializing into a local type.
    
    let file_path = {
      let mut file_buf = PathBuf::new();
      file_buf.push(file_path);
      file_buf
    };

    Self {
      file_path,
      // other fields which are derived from work done on the file
    }
  }
}

(Please ignore that I'm not wrapping the return in a Result<..>, I'll do proper error handling in the real implementation.)

The idea here is, I want to know the path where I got the data, so that I can save back to that file at a later point.

The above code does work, but I fell I can do better.

  1. Can I create the PathBuf directly from the generic impl AsRef<Path> without that clunky interim step? or..
  2. Is there someway to leverage cow or similar?

I don't mind allocating at this stage, but would still prefer a more idiomatic solution, if one exists?

How would y'all implement this?

2 posts - 2 participants

Read full topic

🏷️ rust_feed