英文:
Is there a concise way to check if an Option is None or if its Some contents are empty?
问题
let player_list: Option<Vec<Player>>;
// more code here
if player_list.as_ref().map(|list| list.is_empty()).unwrap_or(true) {
// do something here if player_list is none or empty
}
英文:
Is there something more concise that the below code?
let player_list: Option<Vec<Player>>;
// more code here
if player_list.is_none() || player_list.as_ref().unwrap().is_empty() {
// do something here if player_list is none or empty
}
I would like to avoid the ||
part.
答案1
得分: 6
我假设你可能不希望 player_list
被消耗。在这种情况下,请使用:
player_list.as_ref().map_or(true, Vec::is_empty)
如果可以消耗 player_list
:
player_list.unwrap_or_default().is_empty()
英文:
I assume you probably don't want player_list
to be consumed. In that case, use:
player_list.as_ref().map_or(true, Vec::is_empty)
if it's ok to consume player_list
:
player_list.unwrap_or_default().is_empty()
答案2
得分: 1
你可以使用.map_or
或者.map_or_else
来完成这个任务。
if player_list.map_or(true, |player| player.is_empty()) {
// 魔法
}
当然,是否更容易维护取决于你。
英文:
You can do this with a .map_or
or even .map_or_else
if player_list.map_or(true, |player| player.is_empty()) {
// magic
}
Of course it is up to you if this is more maintanable.
答案3
得分: 0
很难在不查看整个代码上下文的情况下提出明智的建议。所以,如果我下定论,提前道歉。
拥有一个Option
的Vec
有点奇怪。因为Vec
已经是一个集合,它可以是空的。所以,在某种程度上,None
和Vec()
几乎是相同的。
如果None
和Vec()
之间没有实质性的区别,那么也许将player_list
转换为Vec会更好。
在答案中有很好的建议,比如Caesar的答案:
player_list.unwrap_or_default()
如果None
和Vec()
之间有实质性的区别。那么也许拥有一个表示这些不同状态的具体类型会让事情更容易理解。在这种情况下,您可能会吸收代码在这种新类型中应该如何行为的不同方式。
例如:
enum GameStatus {
LobbyNotOpen,
LobbyOpen(Vec<Player>),
}
或者
enum TeamRecruitment {
NotStarted,
OpenForRecruitment(Vec<Player>),
}
英文:
It is hard to make an educated suggestion without looking at the entire context of the code. So, apologies in advance if I am jumping to conclusions.
Having an Option
of Vec
is a bit weird. Since Vec
is already a collection, it can be empty. So, in a way None
is more or less the same as Vec()
.
If there is no meaningful difference between None
and Vec()
, then maybe converting player_list
to Vec would be better.
And there are good suggestions in the answers, for example Caesar's answer:
player_list.unwrap_or_default()
If there is a meaningful difference between None
and Vec()
. Then maybe having a concrete type that represents these different states would make things easier to understand. In that case you'd probably absorb the different ways the code should behave in that new type.
For example:
enum GameStatus {
LobbyNotOpen,
LobbyOpen(Vec<Player>),
}
or
enum TeamRecruitment {
NotStarted,
OpenForRecruitment(Vec<Player>),
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论