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.
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.
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.
In addition to what has already been written, depending on your use case, String::from_utf8_lossy()
might be a good-enough solution.
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.