There are a lot of methods you could have used instead of unwrapping the result from String::from_utf8() if you want to avoid a panic with invalid utf-8. Some options off the top of my head:
- Use
String::from_utf8_lossy() - Change the function signature to return
Result<String, Box<dyn Error>>and use the?operator to safely unwrap or bubble the error to the caller. - Stick with
Vec<u8>and handle the decoding yourself, e.g. with theencoding_rscrate.
I also noticed some other suspicious things elsewhere in that example, which while off-topic does hint at deeper problems with an understanding of the language:
//Free the STDIN Handle
ostdin = None;
This isn't needed because:
- This doesn't actually free anything. The
std::io::Stdintype fits into a single pointer-sized slot on the stack. It is backed by anArcsmart pointer providing shared ownership. - The example doesn't read the value of
ostdinafter this point. So normally the compiler will automatically drop it here. At worst, you are wasting a CPU cycle to write a 0 over the pointer in the stack slot. And another CPU cycle to maintain the unusedOptionon the stack. Not to mention the 8-bytes of stack space required to store it. All of this gets optimized away without this unused write. - Even if you tried to use it later, you would be unable because the
Stdinpointer has already been moved out of theOptionby thematchexpression.