The following code works but not sure if it is the right way. A few questions:
Path
or PathBuf
?AsRef
?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.
This question is almost the same as String
vs &str
, if that helps. PathBuf
is String
, &Path
is &str
. So:
Store a PathBuf
if you want the struct to own it. If you don't know what you want, start here.
Store a &Path
if you just want a reference to a path. Depending on what you're doing, this may be what you want, but if you don't know, it's probably not correct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With