Home
| Colors: |

Get the Components of a Directory Path as a Vec in Rust

September 2025

Note that this converts to lossy strings so some info may be lost if the paths have characters that don't otherwise convert.

TODO: Verify UTF-8 is safe from degredation.

use std::path::PathBuf;

fn main() {
  let paths = vec![
    PathBuf::from("file.txt"),
    PathBuf::from("sub-dir/file.txt"),
    PathBuf::from("/at-root.txt"),
    PathBuf::from("/sub-dir/file.txt"),
  ];

  paths.iter().for_each(|path| {
    dbg!(get_path_as_vec(&path));
  });
}

fn get_path_as_vec(path: &PathBuf) -> Vec<String> {
  path
    .components()
    .map(|comp| comp.as_os_str().to_string_lossy().to_string())
    .collect()
}
Output:
[_active_nvim_run:12:5] get_path_as_vec(&path) = [
    "file.txt",
]
[_active_nvim_run:12:5] get_path_as_vec(&path) = [
    "sub-dir",
    "file.txt",
]
[_active_nvim_run:12:5] get_path_as_vec(&path) = [
    "/",
    "at-root.txt",
]
[_active_nvim_run:12:5] get_path_as_vec(&path) = [
    "/",
    "sub-dir",
    "file.txt",
]
end of line