None如果我从方法中获取 a ,是否有提前返回的方法?例子:
pub async fn found_player(id: &str) -> Result<Option<Player>> {
let player = repo // player here is Option<Player>
.player_by_id(id)
.await?; // I would like to use here a magic method to return here immediately if is None with `Ok(None)`
if player.is_none() {
return Ok(None);
}
// Do some stuff here but WITHOUT using player.unwrap(). I would like to have it already unwrapped since is not None
Ok(Some(player))
}
Run Code Online (Sandbox Code Playgroud)
我尝试过类似的事情Ok_or(),但我认为它们现在就是我所需要的。我能怎么做?
我不想使用matchorif else因为我需要尽可能少一些冗长。
可用的最短语法类似于:
let Some(player) = repo.player_by_id(id).await? else {
return Ok(None);
};
// player is Player here
Run Code Online (Sandbox Code Playgroud)
在 Rust 1.65 之前,必须使用 or 来match拼写if let:
let player = match repo.player_by_id(id).await? {
Some(player) => player,
None => return Ok(None),
};
// player is Player here
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
463 次 |
| 最近记录: |