我想做什么:
enum Test {
Value1,
Value2,
Value3
}
fn main() {
let mut test_vec: Vec<Test> = Vec::new();
test_vec.push(Test::Value2);
if let Some(last) = test_vec.last() {
test_vec.push(*last);
}
//Wanted output: vector with [Test::Value2, Test::Value2]
}
Run Code Online (Sandbox Code Playgroud)
我明白,当我打电话时last(),它会返回Option<&Test>
所以它会借用test_vec直到if-let块结束.
我尝试了以下但没有成功:
if let Some(last) = test_vec.last().map(|v| v.clone()) {
test_vec.push(*last);
}
//and
let last = test_vec.last().unwrap().clone();
test_vec.push(*last);
Run Code Online (Sandbox Code Playgroud) 有没有办法“拉”出数据Option?我有一个 API 调用返回Some(HashMap). 我想使用HashMap它,就好像它不在里面一样Some并使用数据。
根据我所阅读的内容,它看起来Some(...)仅适用于匹配比较和一些内置函数。
从 crate 文档中提取的简单 API 调用:
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(())
}
Run Code Online (Sandbox Code Playgroud)
结果:
Some("75.69.138.107")
Run Code Online (Sandbox Code Playgroud)