Map to Option<String> when unwrapping a Result coming from a function with generic return parameter

In a project, I'm currently using postgres and after querying for data I want to handle possible null database fields by using try_get from the postgres crate.

I want to basically convert the Result into an Option to use None as way of representing null in the database.

I implemented it like this:

let field = row.try_get("field");                     
let field = match field {                             
    Ok(field) => Some(field),                         
    Err(e) => None,                                         

Instead of writing five lines of code for this, I would like to make it one.
I tried:

let field: Option<String> = row.try_get("field").or(Ok(None)).unwrap();

The problem is, that try_get can not infer the type when doing it this way, but I also don't want to call it with the whole type definition because I feel like there must be a better solution.
Am I right, or do I have to do it that way:

let field: Option<String> = row.try_get::<Result<String, some::Error>>("field").or(Ok(None)).unwrap();

I really appreciate any kind of help!

Result::ok() will do what you ask, just call .ok()!


Wow....I feel like an idiot now.
I totally missed that function so far.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.