Take for example working with file names and paths. In for example Linux paths are a collection and bytes and does not need to be valide unicode. Which some programming languages hides from you and subtly introduces errors. Or even worse, accepting that strings may contain invalid unicode poisoning the entire language with uncertainty.
If you are iterating over the files in a directory the Rust standard library gives you paths. Not strings.
To convert a path that to a regular string type which is valid unicode you need to acknowledge that the path may be invalid. Either unwrapping and panicking or handling the error.
To do this the standard library gives two options:
/// Yields a [`&str`] slice if the `Path` is valid unicode.
///
/// This conversion may entail doing a check for UTF-8 validity.
/// Note that validation is performed because non-UTF-8 strings are
/// perfectly valid for some OS.
pub fn to_str(&self) -> Option<&str>
https://doc.rust-lang.org/std/path/struct.PathBuf.html#metho...Or accept that the conversion may be lossy:
/// Converts a Path to a Cow<str>.
///
/// Any non-UTF-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
pub fn to_string_lossy(&self) -> Cow<'_, str>
https://doc.rust-lang.org/std/path/struct.PathBuf.html#metho...You get to make a choice, and panicking/erroring is perfectly valid if you only expect valid unicode paths.
As the world and your software changes if you suddenly encounter a non-unicode path then you will immediately know where the error comes from and can fix the issue. Instead of trying to pinpoint the root source of an error far exposing itself far down stream.