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.
- Can I create the
PathBuf
directly from the genericimpl AsRef<Path>
without that clunky interim step? or.. - 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?