Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
997 views
in Technique[技术] by (71.8m points)

rust - Possible to combine assignment and comparison in an expression?

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);

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;
    }
}

Which works the same as the C version (assuming the body of the loop doesn't use continue).

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.

For example, as an integer:

n = n_init;
loop {
    func(&vec[n]);
    n = vec[n].next;
    if n == n_init {
        break;
    }
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...