How to display non-English characters when deal with the Path

Hi,if the file name include non-English character,how to display them?

use std::path::Path;


fn main() {
    let path = Path::new("世界");
    let s="世界";

    println!("{:?}",path );
    println!("{}",s);
}

Output:

"\u{4e16}\u{754c}"
世界

You have to convert it to a string:

use std::path::Path;

fn main() {
    let path = Path::new("世界");
    let s = "世界";

    println!("{:?}", path);
    println!("{}", path.to_str().unwrap_or("{invalid}"));
    println!("{}", s);
}

The problem is that Paths are internally OsStrs, and OsStrs might not be valid strings at all. So, if you want to Display them, you have to explicitly convert them into something which can be Displayed.

1 Like

:slightly_smiling: Thanks.

I have tried this before but forgot to unwrap and used the {:?} marker,so the output of println!("{:?}", path.to_str()) is “Some("\u{4e16}\u{754c}")”. I thought maybe it was some encode problem but still do not know how to solve。I really appreciate your patience in answering my question

Don't miss the method Path::display()!

println!("{}", path.display());
5 Likes