How to mutate the underlying String of a PathBuf?

Viewed 81

I want a function that mutates the underlying String of a PathBuf object, but all I could achieve now is creation of a new object instead.

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

fn expanduser(path: &mut PathBuf) -> PathBuf {
    return PathBuf::from(
        &path
            .to_str()
            .unwrap()
            .replace("~", PathBuf::home().to_str().unwrap()),
    );
}
1 Answers

PathBuf wraps an OsString, not a String. They are much different types - String contains a UTF-8 string while OsString depends on the platform: arbitrary bytes for Unix and potentially-malformed UTF-16 on Windows.

You can use into_os_string to convert a PathBuf to an OsString, and From for the reverse.

If you are just trying to replace ~ with the home path, your best bet is to check if the first component (via the components method) is a Normal component containing "~" and join the rest of the components to the home path if so. There's crates that do this for you.

I hate that function, cause if the path I'm canonicalizing doesn't exist, it throws an error instead of gracefully doing what it should do. No one asked it to check existence.

You're likely misunderstanding the function. canonicalize resolves symlinks, so of course it won't work if the path doesn't exist. Also worth mentioning is that foo/bar/../baz is NOT necessarily the same as foo/baz, if foo/bar is a symlink.

Related