如何从 Option 中提取数据以供独立使用? [英] How can I pull data out of an Option for independent use?
问题描述
有没有办法从 Option
中拉出"数据?我有一个返回 Some(HashMap)
的 API 调用.我想使用 HashMap
就好像它不在 Some
中一样使用数据.
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.
根据我读过的内容,看起来 Some(...)
仅适用于匹配比较和一些内置函数.
Based on what I've read, it looks like Some(...)
is only good for match comparisons and some built-in functions.
从 crate 文档中提取的简单 API 调用:
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(())
}
结果:
Some("75.69.138.107")
推荐答案
if let Some(origin) = resp.get("origin") {
// use origin
}
如果你能保证值不可能是None
,那么你可以使用:
If you can guarantee that it's impossible for the value to be None
, then you can use:
let origin = resp.get("origin").unwrap();
或者:
let origin = resp.get("origin").expect("This shouldn't be possible!");
而且,由于您的函数返回一个 Result
:
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)?;
这篇关于如何从 Option 中提取数据以供独立使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!