What is the idiomatic way to create a Path from &str fragments?

Hello. I want to manipulate files that all are in a common directory, and share the same extension. In shell, I would do:


What is the idiomatic way to do it in Rust? The following snippet works, but it's just one of the many way to do it. Is there as standard way?

use std::path::Path;
const BASE_DIRECTORY: &str = "/some/folder";

fn read_data_from_city(city: &str) -> Vec<f64> {
    let path = Path::new(BASE_DIRECTORY).join([city, ".txt"].concat());
    // open path and read data

EDIT: I noticed that I can't create a const Path so I modified BASE_DIRECTORY to be &str.

Under the assumption you control the format of the path components, I think one needs to clarify why

const BASE_DIRECTORY: &str = "/some/folder/";
let path = [BASE_DIRECTORY, city, ".txt"].concat();

does not suffice.

Mostly because there are so many way to do the same thing, that I don't know which one to choose, and the tradeoff aren't clear. Hence my question, what is the idiomatic way to do it.

The std::path module documentation lists let path: PathBuf = ["some", "string", "fragments"].iter().collect(); as the best way to turn a number of &str path fragments known up front into a path.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.