Change The Root Directories Of A File Path In Rust
    
    
    May 2024
    
   
This is how I replace the starting portion of a rust PathBuf:
---
[dependencies]
anyhow = "1.0.98"
---
use anyhow::Result;
use std::path::PathBuf;
fn main() -> Result<()> {
  let source = PathBuf::from("/some/path/to/a/file.txt");
  let find = PathBuf::from("/some/path");
  let replacement = PathBuf::from("/another/method");
  let result = replace_path_root(&source, &find, &replacement)?;
  println!("{}", result.display());
  Ok(())
}
pub fn replace_path_root(
  source: &PathBuf, 
  find: &PathBuf, 
  replacement: &PathBuf
) -> Result<PathBuf> {
  let stripped_path = source.strip_prefix(find)?;
  let new_path = replacement.clone().join(stripped_path);
  Ok(new_path)
}
/another/method/to/a/file.txt