Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replacing Unwrap()s with ? – Compiler Complaining on Functions That Do Return Result or Option

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

This function here refers to the outer function. That is, the function you are writing, not from_utf8.

? will return an error from your function if there was one, thus your function needs the right return type to be able to return an error.

Because from_utf8 is not the source of the issue, you’d get the same error like this too:

let r = Err(...);
let json = r?;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading