Skip to content

Rust is eagerly evaluating range causing inconsistencies #72763

Closed

Description

@eloraiby

Following this small example:

#[cfg(test)]
mod tests {
    #[test]
    fn test_for() {
        let mut v = Vec::new();
        for i in 0..10 {
            v.push(i);
        }

        for i in 0..v.len() {
            if i < 100 {
                v.push(i);
            }
        }

        assert!(v.len() == 110); // Crash! expected 110, count is 20
    }

    #[test]
    fn test_loop() {
        let mut v = Vec::new();
        for i in 0..10 {
            v.push(i);
        }

        let mut i = 0;
        loop {
            if i >= v.len() {
                break;
            }

            if i < 100 {
                v.push(i);
            }

            i += 1;
        }

        assert!(v.len() == 110);
    }

}

If that's the normal behaviour, it should be documented in https://doc.rust-lang.org/std/ops/struct.Range.html, in the language references and tutorials.

The behaviour as it stands is in contrast of what other languages implements and is confusing.

Activity

  1. jonas-schievink commented on May 30, 2020

    @jonas-schievink
    Contributor

    Nothing in Rust is lazily evaluated. Evaluation order of language constructs like for and the range syntax is in scope of https://github.com/rust-lang/reference/.

  2. eloraiby commented on May 30, 2020

    @eloraiby
    Author

    @jonas-schievink you failed to provide where in that reference! - if it's in there -

  3. jonas-schievink commented on May 30, 2020

    @jonas-schievink
    Contributor

    It isn't documented yet – but this is being tracked in rust-lang/reference#248

  4. eloraiby commented on May 30, 2020

    @eloraiby
    Author
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions