问题描述
在 C 中,通常在单个表达式中进行赋值和比较:
In C, it's common to assign and compare in a single expression:
n = n_init;
do {
func(n);
} while ((n = n.next) != n_init);
据我所知,这可以用 Rust 表示为:
As I understand it this can be expressed in Rust as:
n = n_init;
loop {
func(n);
n = n.next;
if n == n_init {
break;
}
}
与 C 版本的工作方式相同(假设循环体不使用 continue
).
Which works the same as the C version (assuming the body of the loop doesn't use continue
).
在 Rust 中是否有更简洁的表达方式,或者上面的示例是否理想?
Is there a more terse way to express this in Rust, or is the example above ideal?
就本问题而言,假设所有权或满足借用检查器不是问题.满足这些要求取决于开发者.
For the purposes of this question, assume ownership or satisfying the borrow checker isn't an issue. It's up to developer to satisfy these requirements.
例如,作为整数:
n = n_init;
loop {
func(&vec[n]);
n = vec[n].next;
if n == n_init {
break;
}
}
这似乎很明显,Rust 示例是惯用的 Rust - 但是我希望将很多这种风格的循环移动到 Rust,我很想知道是否有更好/不同的方式来表达它.
This may seem obvious that the Rust example is idiomatic Rust - however I'm looking to move quite a lot of this style of loop to Rust, I'm interested to know if there is some better/different way to express it.
推荐答案
在 Rust 中表示迭代的惯用方式是使用 Iterator
.因此,您将实现一个执行 n = n.next
的迭代器,然后使用 for
循环遍历迭代器.
The idiomatic way to represent iteration in Rust is to use an Iterator
. Thus you would implement an iterator that does the n = n.next
and then use a for
loop to iterate over the iterator.
struct MyIter<'a> {
pos: &'a MyData,
start: &'a MyData,
}
impl<'a> Iterator for MyIter<'a> {
type Item = &'a MyData;
fn next(&mut self) -> Option<&'a MyData> {
if self.pos as *const _ == self.start as *const _ {
None
} else {
let pos = self.pos;
self.pos = self.pos.next;
Some(pos)
}
}
}
读者可以练习修改这个迭代器,使其能够从第一个元素开始,而不是从第二个元素开始.
it is left as an exercise to the reader to adapt this iterator to be able to start from the first element instead of starting from the second.
这篇关于可以在表达式中结合赋值和比较吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!