Search code examples
rustpathcross-platformplatformplatform-independent

How to prepend "./" to a path in a platform independent way?


I need to prepend ./ to paths in my code, which I'm currently doing like this:

let path = Path::new("foo.sol");
let path_with_dot = Path::new("./").join(path);

However, I want to maintain compatibility across multiple platforms while adding ./ in front of the path. How can I do this?


Solution

  • A platform dependent const for path separators is stored at std::path::MAIN_SEPARATOR. You can use this to create platform dependent paths. However, by default the Path.join method already uses this const so instead of writing:

    let path = Path::new("foo.sol");
    let path_with_dot = Path::new("./").join(path);
    

    You would just write:

    let path = Path::new("foo.sol");
    let path_with_dot = Path::new(".").join(path);
    

    And the result will automatically be platform dependent.