Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I deserialize a document from MongoDB into a Rust struct? [duplicate]

Tags:

rust

I want to write the following with if let but Ok(config) does not provide the type for toml::from_str

let result: Result<Config, _> = toml::from_str(content.as_str());
match result {
    Ok(config) => {}
    _ => {}
}

// if let Ok(config) = toml::from_str(content.as_str()) {
//    
// }

I tried Ok(config: Config) without luck. The success type is not inferred.

like image 582
Pascal Avatar asked Nov 17 '22 08:11

Pascal


1 Answers

This has nothing to do with the match or the if let; the type specification is provided by the assignment to result. This version with if let works:

extern crate toml;

fn main() {
    let result: Result<i32, _> = toml::from_str("");
    if let Ok(config) = result {
        // ... 
    }
}

This version with match does not:

extern crate toml;

fn main() {
    match toml::from_str("") {
        Ok(config) => {}
        _ => {}
    }
}

In most cases, you'll actually use the success value. Based on the usage, the compiler can infer the type and you don't need any type specification:

fn something(_: i32) {}

match toml::from_str("") {
    Ok(config) => something(config),
    _ => {}
}

if let Ok(config) = toml::from_str("") {
    something(config);
}

If for some reason you need to perform the conversion but not use the value, you can use the turbofish on the function call:

match toml::from_str::<i32>("") {
//                  ^^^^^^^
    Ok(config) => {},
    _ => {}
}

if let Ok(config) = toml::from_str::<i32>("") {
    //                            ^^^^^^^
}

See also:

  • How do I imply the type of the value when there are no type parameters or ascriptions?
like image 181
Shepmaster Avatar answered Jun 12 '23 06:06

Shepmaster