我可以跳过在 for 循环之前对空向量的检查吗?

huangapple go评论59阅读模式
英文:

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&lt;Vec&lt;T&gt;&gt; where you will need to check before iterating.

huangapple
  • 本文由 发表于 2023年5月28日 08:28:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76349533.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定