rustiteratorrange

Why is &Range<T> not an iterator, but &mut Range<T> is?


Demo code using version rustc 1.86.0 (05f9846f8 2025-03-31)

fn main() {
    let mut source = 1..3;

    test(&mut source); // This is good. which means &mut Range<T> is Iterator. 

    test(&source); // This code error "`&std::ops::Range<{integer}>` is not an iterator"
}

fn test(i: impl Iterator<Item = i32>) {
    for i in i {
        println!("{}", i);
    }
}

I didn't find the reason from source code of rust.


Solution

  • This has nothing to do with Range. All mutable references to iterators implement Iterator due to this implementation. However to be able to iterate requires mutating the iterator's state, which can't be done through an immutable reference so there is no such implementation.