How to convert the PathBuf to String

前端 未结 3 1931
温柔的废话
温柔的废话 2020-12-15 03:31

I have to convert the PathBuf variable to a String to feed my function. My code is like this:

let cwd = env::current_dir().unwrap()         


        
相关标签:
3条回答
  • 2020-12-15 04:11

    As mcarton already say is not so simple and not all path are UTF-8 encoded. But you can use:

    p.into_os_string().into_string()
    

    To have a fine control of it. By ? you can send error to upper level or simply ignore it by unwrap():

    let my_str = cwd.into_os_string().into_string().unwrap();
    

    The beauty thing about into_string() is that the error wrap the original OsString value.

    0 讨论(0)
  • 2020-12-15 04:18

    It is not easy on purpose: String are UTF-8 encoded, but PathBuf might not be (eg. on Windows). So the conversion might fail.

    There are also to_str and to_string_lossy methods for convenience. The former returns an Option<&str> to indicate possible failure and the later will always succeed but will replace non-UTF-8 characters with U+FFFD REPLACEMENT CHARACTER (which is why it returns Cow<str>: if the path is already valid UTF-8, it will return a reference to the inner buffer but if some characters are to be replaced, it will allocate a new String for that; in both case you can then use into_owned if you really need a String).

    0 讨论(0)
  • 2020-12-15 04:29

    One way to convert PathBuf to String would be:

    your_path.as_path().display().to_string();

    0 讨论(0)
提交回复
热议问题