Result
and_then
然后你
然后你
方法可以调用):
enum Good {
Ok,
Good,
VeryGood,
}
enum Pizza {
Tomato,
Pineapple,
}
enum Burger {
Cow,
}
enum Food {
Pizza(Pizza),
Burger(Burger),
}
fn main() {}
fn s(r: Result<Good, ()>) -> Result<Food, ()> {
r.and_then(|o| {
match o {
// Should be called in the next and_then block
Good::Ok => Ok(Pizza::Tomato),
// Should be called in the next and_then block
Good::Good => Ok(Pizza::Pineapple),
Good::VeryGood => {
// I am done. Don't call the next and_then block, but rather return the whole value to the caller.
return Ok(Food::Burger(Burger::Cow));
}
}
})
.and_then(|p: Pizza| {
// At this point, the closure input value should be pizza, because that's the only returned value
Ok(Food::Pizza(p))
})
}
Playground
error[E0308]: mismatched types
--> src/main.rs:30:27
|
30 | return Ok(Food::Burger(Burger::Cow));
| ^^^^^^^^^^^^^^^^^^^^^^^^^ expected enum `Pizza`, found enum `Food`
|
= note: expected type `Pizza`
found type `Food`
我希望有办法使它编译。我可以打破这个方法
,但也许有办法
.
在我的真实代码中,我有更多
然后你
它将类型映射到其他类型、错误映射等,因此这是我所面临问题的简化复制路径。
这是从我的代码库复制粘贴的代码,显示
然后你
然后你
User
(尽管它目前不起作用)。一个选项是不链接块并创建单独的值,但我希望可以在闭包中直接将值返回给调用方。
db_session
.query_with_values(query, values)
.map_err(|e| {
error!("{:?}", e);
TechnicalServerError::SERVER_RETRY
})
.and_then(|f| {
f.get_body().map_err(|e| {
error!("{:?}", e);
TechnicalServerError::SERVER_RETRY
})
})
.and_then(|b| b.into_rows().ok_or(TechnicalServerError::SERVER_RETRY))
.and_then(|mut c| {
if let Some(row) = c.pop() {
User::try_from_row(row).map_err(|e| {
error!("{:?}", e);
TechnicalServerError::SERVER_INVALID
})
} else {
return Ok(Login::Other(LoginResult::UNKNOWN_USER));
}
})
.and_then(|u| {
// 'u' should be of type 'user' at this point
// some user code here...
})