Home

Getting An Absolute PathBuf Path In Rust With Leading Slash

".strip_prefix()" removes leading slashes.

rust
use std::path::PathBuf;

fn main() {
  let dir_path = PathBuf::from("/alfa/bravo");
  let target_path = PathBuf::from("/alfa/bravo/charlie/delta.html");
  let cut_path = target_path.strip_prefix(dir_path);
  println!("{}", cut_path.unwrap().display());
}
TODO: Show Results Output
rust
use std::path::PathBuf;

fn main() {
  let mut absolute_url = PathBuf::from("/");
  let source_dir = PathBuf::from("/alfa/bravo");
  let source_path = PathBuf::from("/alfa/bravo/charlie/delta.html");
  let relative_path = source_path.strip_prefix(source_dir).unwrap();
  absolute_url.push(relative_path);
  println!("{}", absolute_url.display());
}
TODO: Show Results Output
~ fin ~