英文:
Can I skip the check on empty vec before the for?
问题
以下是翻译好的内容:
如果我有这样的代码:
let players = vec![];
if !players.is_empty() {
for player in players {
// 在这里使用 player
}
}
我可以跳过 .is_empty()
的检查直接使用以下代码吗?
let players = vec![];
for player in players {
// 在这里使用 player
}
英文:
If I have code like this:
let players = vec![];
if !players.is_empty() {
for player in players {
// use player here
}
}
Can I skip the check on .is_empty()
and use directly the below?
let players = vec![];
for player in players {
// use player here
}
答案1
得分: 1
除非您希望在空列表上发生特定行为,比如显示“列表为空”或其他警告或提醒,否则在空列表上进行迭代没有任何问题。
值得注意的是,编译器可能会将所有这些代码都丢弃,因为在创建时Vec
是空的,而且由于它是不可变的,无论如何都不会有条目。在if
语句内的所有内容都是无法访问的。
对于mut players
列表的情况,条目可能会被添加,但即使在空列表上进行迭代也不会出现问题。只有在列表可能为None
的情况下,比如Option<Vec<T>>
,在进行迭代之前需要进行检查。
英文:
Unless you're looking for specific behaviour to happen on an empty list, like saying "List is empty" or some other warning or alert, there's really no harm in iterating over nothing.
It's worth noting that here the compiler may well throw all of this code out as that Vec
is empty when created, and as it's immutable, can never have entries anyway. Everything inside that if
is unreachable.
In the case of a mut players
list where entries might be added you still have no problems iterating over an empty list. It's only where the list might be None
, as in Option<Vec<T>>
where you will need to check before iterating.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论