home ~ projects ~ socials

Change A File Path's Extension In Rust

Switch It Up

Use .set_extension() to change the extension of a file path.

This is directly from the docs page (which is an example of 10/10 set of example code)

use std::path::{Path, PathBuf};

fn main() {

  let mut p = PathBuf::from("/feel/the");

  p.set_extension("force");
  assert_eq!(Path::new("/feel/the.force"), p.as_path());

  p.set_extension("dark.side");
  assert_eq!(Path::new("/feel/the.dark.side"), p.as_path());

  p.set_extension("cookie");
  assert_eq!(Path::new("/feel/the.dark.cookie"), p.as_path());

  p.set_extension("");
  assert_eq!(Path::new("/feel/the.dark"), p.as_path());

  p.set_extension("");
  assert_eq!(Path::new("/feel/the"), p.as_path());

  p.set_extension("");
  assert_eq!(Path::new("/feel/the"), p.as_path());

  println!("See tests for the example");

}
Output:
See tests for the example
-- end of line --