Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pull data out of an Option for independent use?

Is there a way to 'pull' data out of an Option? I have an API call that returns Some(HashMap). I want to use the HashMap as if it weren't inside Some and play with the data.

Based on what I've read, it looks like Some(...) is only good for match comparisons and some built-in functions.

Simple API call pulled from crate docs:

use std::collections::HashMap;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let resp = reqwest::blocking::get("https://httpbin.org/ip")?
        .json::<HashMap<String, String>>()?;
    println!("{:#?}", resp.get("origin"));
    Ok(())
}

Result:

Some("75.69.138.107")
like image 833
seamus Avatar asked Nov 25 '20 00:11

seamus


Video Answer


2 Answers

if let Some(origin) = resp.get("origin") {
    // use origin
}

If you can guarantee that it's impossible for the value to be None, then you can use:

let origin = resp.get("origin").unwrap();

Or:

let origin = resp.get("origin").expect("This shouldn't be possible!");

And, since your function returns a Result:

let origin = resp.get("origin").ok_or("This shouldn't be possible!")?;

Or with a custom error type:

let origin = resp.get("origin").ok_or(MyError::DoesntExist)?;
like image 199
Peter Hall Avatar answered Nov 15 '22 11:11

Peter Hall


Your options are a plenty.

if let Some(origin) = resp.get("origin") {
    // do stuff using origin
}
origin = resp.get("origin").unwrap()
// will panic if None
resp.get("origin").map(|origin| {
    // do stuff using inner value, returning another option
})
resp.get("origin").and_then(|origin| {
    // same as map but short-circuits if there is no inner value
})
like image 21
Ivan C Avatar answered Nov 15 '22 10:11

Ivan C