rust-lang / rust-lang/rust

The `Zip` iterator does not update the underlying iterator correctly in its `TrustedLen` specialization.

Open
#144,012 3 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

A-iterators A-specialization C-discussion T-libs
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I tried this code:

pub fn using_each() {
    let mut it = 0..4;
    it.by_ref().zip(0..2).for_each(|_| {});
    println!("{:?}", it);
}

pub fn using_loop() {
    let mut it = 0..4;
    for _ in it.by_ref().zip(0..2) {}
    println!("{:?}", it);
}

pub fn using_each_dyn() {
    let mut it = 0..4;
    (&mut it as &mut dyn Iterator<Item = i32>).zip(0..2).for_each(|_| {});
    println!("{:?}", it);
}

pub fn using_loop_dyn() {
    let mut it = 0..4;
    for _ in (&mut it as &mut dyn Iterator<Item = i32>).zip(0..2) {}
    println!("{:?}", it);
}

fn main() {
    using_each();
    using_loop();
    using_each_dyn();
    using_loop_dyn();
}

I expected all four functions to behave identically, but instead the above code outputs:

2..4
3..4
3..4
3..4

This occurs because:

This mismatch in behavior seems undesirable.

Discovered in #143966.

Meta

Reproducible on the playground with version 1.90.0-nightly (2025-07-15 3014e79f9c8d5510ea7b)

@rustbot labels +A-iterators +A-specialization

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with library/core/src/iter/adapters/zip.rs around the TrustedLen-specialized fold implementation and reproduce the four iterator examples from the issue. Compare the specialized and general Zip consumption paths, then verify that the chosen behavior is consistent and covered by an appropriate regression test.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.