How to convert the PathBuf to String

前端 未结 3 1930
温柔的废话
温柔的废话 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条回答
  •  萌比男神i
    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: 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).

提交回复
热议问题