Error handling and UTF-8 validation

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 the encoding_rs crate.

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:

  1. This doesn't actually free anything. The std::io::Stdin type fits into a single pointer-sized slot on the stack. It is backed by an Arc smart pointer providing shared ownership.
  2. The example doesn't read the value of ostdin after 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 unused Option on 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.
  3. Even if you tried to use it later, you would be unable because the Stdin pointer has already been moved out of the Option by the match expression.
7 Likes