Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join Path from multiple parts of different type in Rust?

Tags:

rust

Documentation provides following example for joining paths:

use std::path::PathBuf;

let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();

This works when all the components are strings. However, I am trying to write following function:

use std::path::PathBuf;
fn my_path<P: AsRef<Path>>(root: P, dir1: &str, dir2: &str, dir3: &str) -> PathBuf {
    [root, dir1, dir2, dir3].iter().collect()
}

The above obviously doesn't work. I know I can do series of nested joins, but that is, ..., more ugly.

Is there a way to join different path-like components in array?

like image 848
Samuel Hapak Avatar asked Nov 19 '25 17:11

Samuel Hapak


1 Answers

You can cast them to dynamic AsRef<Path> objects:

use std::path::{Path, PathBuf};
fn my_path<P: AsRef<Path>>(root: P, dir1: &str, dir2: &str, dir3: &str) -> PathBuf {
    [&root as &dyn AsRef<Path>, &dir1, &dir2, &dir3].iter().collect()
}

or just add the first different object with join:

use std::path::{Path, PathBuf};
fn my_path<P: AsRef<Path>>(root: P, dir1: &str, dir2: &str, dir3: &str) -> PathBuf {
    root.as_ref().join([dir1, dir2, dir3].iter().collect::<PathBuf>())
}

Here it is on Rust Playground

like image 197
cafce25 Avatar answered Nov 21 '25 14:11

cafce25



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!