How to get path.join in Rust?

Viewed 3822

How do I write the path.join in Rust. I tried multiple examples but couldn't get it.

const exeDirectory = path.join(__dirname, '..', 'bin', 'openvpn.exe');
const processFile = path.join(__dirname, '..', '1');

I want to convert these lines of JS into Rust.

3 Answers

Use Path which has the .join method

Path::new("..").join("bin").join("openvpn.exe");

Another option is collecting an iterator of string into a PathBuf:

let path: PathBuf = ["..", "bin", "openvpn.exe"].iter().collect();

This is equivalent to creating a new PathBuf and calling .push() for each string in the iterator. To add multiple new components to an existing PathBuf, you can use the extend() method:

let mut path = PathBuf::from(dir_name);
path.extend(&["..", "bin", "openvpn.exe"]);

I may be missing something but have you looked at Path::join, and PathBuf::push linked from it?

let exe_directory = Path::new(dirname).join("..").join("bin").join("openvpn.exe");
println!("{:?}", exe_directory);


let mut exe_directory = PathBuf::new();
exe_directory.push(dirname);
exe_directory.push("..");
exe_directory.push("bin");
exe_directory.push("openvpn.exe");
println!("{:?}", exe_directory);

Playground link

Related