The following code works but not sure if it is the right way. A few questions:
- Should I use
Path
orPathBuf
? - Should I use
AsRef
? - Do I need
PathBuf::from(path)
in order to have path owned by the struct?
use std::fmt;
use std::path::PathBuf;
struct Example {
path: PathBuf,
}
impl fmt::Display for Example {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.path.to_str().unwrap())
}
}
impl Example {
fn new(path: &PathBuf) -> Example {
// Do something here with path.
Example {
path: PathBuf::from(path),
}
}
}
fn main() {
let x = Example::new(&PathBuf::from("test.png"));
println!("{}", x);
}
Some context: I am trying to have a high-level abstraction over a file that should know its own path. Maybe the design is plain wrong.