xiaoai
xiaoai

Reputation: 1411

How to convert the PathBuf to String

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();
let my_str: String = cwd.as_os_str().to_str().unwrap().to_string();
println!("{:?}", my_str);

it works but is awful with the cwd.as_os_str…. Do you have a more convenient method or any suggestions on how to handle it?

Upvotes: 130

Views: 95684

Answers (5)

Paras Bhattrai
Paras Bhattrai

Reputation: 587

One way to convert PathBuf to String would be:

your_path.display().to_string()

Upvotes: 42

Kaplan
Kaplan

Reputation: 3718

The shortest solution, which also takes Unicode characters into account, as necessary for Windows paths:

let my_str: String = cwd.display().to_string();

Playground

Upvotes: 3

ypwang
ypwang

Reputation: 137

As @mcarton mentioned, to_string_lossy() should do the job.

let cwd = env::current_dir().unwrap();
let path: String =String::from(cwd.to_string_lossy());

rustc 1.56.1 (59eed8a2a 2021-11-01)

I am a (learning) Rust fan (years of c/c++ programmer) but man, if it makes simple thing so complicated, UTF-8 and COW.. makes people lost in the translation.

Upvotes: 7

Michele d'Amico
Michele d'Amico

Reputation: 23711

As mcarton has already said it is not so simple as not all paths are UTF-8 encoded. But you can use:

p.into_os_string().into_string()

In order to have a fine control of it utilize ? to send error to upper level or simply ignore it by calling unwrap():

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

A nice thing about into_string() is that the error wrap the original OsString value.

Upvotes: 105

mcarton
mcarton

Reputation: 29981

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).

Upvotes: 43

Related Questions