How to store a return string?

I am reading files through read_dir function. It returns an iterator of DirEntry.

println!("{:?}", entry.file_name());

here I want to store the entry.file_name() into a String. How do I do it? entry.file_name() returns a OsString.

There is OsString::into_string you could use for the conversion.

2 Likes

In full generality you cannot, since a filename can contain arbitrary bytes, depending on your OS, but String must be valid UTF-8 (this is the reason OsStr[ing] exists in the first place). That's why OsString::into_string returns a Result: the conversion may fail.

7 Likes

In addition to what has already been written, depending on your use case, String::from_utf8_lossy() might be a good-enough solution.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.