Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right way to store an immutable Path in a struct?

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.

like image 710
Hernan Avatar asked Sep 23 '15 03:09

Hernan


1 Answers

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.

like image 84
Steve Klabnik Avatar answered Oct 18 '22 01:10

Steve Klabnik