使用自定义步骤迭代范围的稳定方法是什么? [英] What is a stable way to iterate on a range with custom step?
问题描述
如果我想在稳定的Rust中使用自定义步骤进行迭代,我该怎么办?基本上类似于C / C ++
How should I go if I want to iterate with a custom step in stable Rust? Essentially something like the C/C++
for (int i = 0; i < n; i += 2) {
}
我已经尝试过使用 range_step_inclusive
以及如何使用自定义步骤迭代范围? :
I've already tried using range_step_inclusive
and the solutions in How do I iterate over a range with a custom step?:
use std::iter::range_step_inclusive;
for i in range_step_inclusive(0, n, 2) {
println!("i: {}", i);
}
但似乎它在Rust 1.1中不可用:
But it seems like it isn't available in Rust 1.1:
error: unresolved import `std::iter::range_step_inclusive`. There is no `range_step_inclusive` in `std::iter`
什么是替代品?可能是创建自定义范围的惯用方法。
What would be an alternative? Possibly the idiomatic way for creating custom ranges.
推荐答案
Rust 1.28 +
Iterator :: step_by
现在稳定:
Rust 1.28+
Iterator::step_by
is now stable:
fn main() {
for i in (0..100).step_by(2) {
println!("{}", i);
}
}
Rust 1.1 +
你总是可以用老式的方式写出来:
Rust 1.1+
You can always write it out the old-fashioned way:
fn main() {
let mut i = 0;
while i < 100 {
println!("i: {}", i);
i += 2;
}
}
然后可以抽象出来:
use std::ops::Add;
fn step_by<T, F>(start: T, end_exclusive: T, step: T, mut body: F)
where
T: Add<Output = T> + PartialOrd + Copy,
F: FnMut(T),
{
let mut i = start;
while i < end_exclusive {
body(i);
i = i + step;
}
}
fn main() {
step_by(0, 100, 2, |i| {
println!("i: {}", i);
})
}
有趣的历史旁注我相信最初所有的循环都是用这样的闭包来完成的,之后迭代器变得非常普遍。
Interesting historical side note, I believe that originally all the looping was done with closures like this, before iterators became extremely prevalent.
然后你可以把它变成迭代器:
You can then take this and make it into an iterator:
use std::ops::Add;
struct StepBy<T> {
start: T,
end_exclusive: T,
step: T,
}
impl<T> StepBy<T> {
fn new(start: T, end_exclusive: T, step: T) -> Self {
Self {
start,
end_exclusive,
step,
}
}
}
impl<T> Iterator for StepBy<T>
where
T: Add<Output = T> + PartialOrd + Copy,
{
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
if self.start < self.end_exclusive {
let v = self.start;
self.start = self.start + self.step;
Some(v)
} else {
None
}
}
}
fn main() {
for i in StepBy::new(0, 100, 2) {
println!("i: {}", i);
}
}
参见:
- How can I add new methods to Iterator?
这篇关于使用自定义步骤迭代范围的稳定方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!