I'm only a few days into my Rust journey and going over my now functionally completed first project, working on exercising unwrap()
s from my code.
The first two instances I've tried, I've completely failed and I cannot work out why. I have this line in my code:
let json = str::from_utf8(&buf).unwrap();
from_utf8
returns Result<&str, Utf8Error>
, but trying:
let json = str::from_utf8(&buf)?;
Has a compiler error of "This function should return Result or Option to accept ?", but it does return Result
. I can only assume that the pointer &
is having an effect here?
I've refactored this now to:
match str::from_utf8(&buf) {
Ok(json) => {
let msg: MyMessage = serde_json::from_str(json).unwrap();
self.tx.try_send((msg, src)).expect("Could not send data");
}
Err(e) => {}
};
I still need to work out what to do in the Err
but I've gotten rid of the unwrap()
call. However, there's another.
serde_json::from_str(json).unwrap();
This returns Result<T>
, so:
serde_json::from_str(json)?;
This is also complaining about the fact it should return Result
when it already does.
At this point, it's safe to assuming I'm really confused and I don't understand half as much as a thought I did.
Countless blogs just say use ?
, yet, in every instances I think it should work and the return types appear suitable, the compiler says no.
Would the From
trait work here? Is it common to have to write traits like this?