Skip to content

Rust is eagerly evaluating range causing inconsistencies #72763

Closed
@eloraiby

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.

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