31

The following code works but not sure if it is the right way. A few questions:

  • Should I use Path or PathBuf?
  • 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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Hernan
  • 5,811
  • 10
  • 51
  • 86

1 Answers1

38

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.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
Steve Klabnik
  • 14,521
  • 4
  • 58
  • 99