rust 如果我从一个方法中得到'None',是否有一个方法可以提前返回?

yqkkidmi  于 2022-11-12  发布在  其他
关注(0)|答案(2)|浏览(154)

如果我从一个方法得到一个None,是否有一个方法可以提前返回?例如:

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))
}

我试过像Ok_or()这样的东西,但我认为它们现在是我所需要的。我该怎么做呢?
我不想使用matchif else,因为我需要尽可能少的冗长。

0qx6xfy6

0qx6xfy61#

可用的最短语法如下所示:

let Some(player) = repo.player_by_id(id).await? else {
    return Ok(None);
};
// player is Player here

在Rust 1.65之前,它必须用matchif let来拼写:

let player = match repo.player_by_id(id).await? {
    Some(player) => player,
    None => return Ok(None),
};
// player is Player here
e5njpo68

e5njpo682#

这有什么不对吗?

pub async fn found_player(id: &str) -> Result<Option<Player>> {
    Ok(repo // player here is Option<Player>
        .player_by_id(id)
        .await?
        .map(|p: Player| {
            // do something with p
        }))
}

我不明白为什么要在这里使用Result,因为您的代码从来不返回Err case。

相关问题