Sender and ExactSizeIterator?

Is that normal ???

use std::sync::mpsc::channel;
use std::iter::repeat;

fn main(){
    let (tx, rx) = channel::<f32>();
    let a = repeat(tx.clone()).take(5);
    a.len();
}

->

error[E0599]: no method named `len` found for struct `std::iter::Take<std::iter::Repeat<std::sync::mpsc::Sender<f32>>>` in the current scope
    --> src/main.rs:7:7
     |
7    |       a.len();
     |         ^^^ method not found in `std::iter::Take<std::iter::Repeat<std::sync::mpsc::Sender<f32>>>`
     |
     = note: the method `len` exists but the following trait bounds were not satisfied:
             `std::iter::Repeat<std::sync::mpsc::Sender<f32>>: std::iter::ExactSizeIterator`
             which is required by `std::iter::Take<std::iter::Repeat<std::sync::mpsc::Sender<f32>>>: std::iter::ExactSizeIterator`

This has nothing to do with Senders, and instead has to do with Iterators. I assume that ExactSizeIterator can't be implemented for this std::iter::Take, since the underlying iterator may not yield the correct number of elements. In this case it's because std::iter::Repeat doesn't implement ExactSizedIterator, since it returns an infinite amount of elements. You can't put an integer value to that, so implementing ExactSizedIterator would be meaningless.

1 Like

To add to that, this could potentially work if we had a trait InfiniteSizeIterator for iterators guaranteed to always return an element, like Repeat (and specialization so that we could have an ExactSizeIterator impl for Take where T: InfinitesizeIterator as well as for T: ExactSizeIterator). But since we don't, this isn't feasible.

1 Like

Ok, thanks.
There are similar problems with flatten

use std::sync::mpsc::channel;
use std::iter::repeat;

fn main(){
  let a = vec!(1, 2, 3);
  let b = vec!(1, 2, 3);
  let c = vec!(a, b).iter().flatten();
  println!("{}", c.len());
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.