Skip to content

type inference bug with take/drop from std::iterator #6967

Closed

Description

@thestinger

The following works (as does drop_while):

use std::iterator::*;

fn main() {
    let _xs = Counter::new(0, 1).take_while(|&x| x < 20).to_vec();
}

However, take and drop run into a type inference bug:

use std::iterator::*;

fn main() {
    let _xs = Counter::new(0, 1).take(20).to_vec();
}
bar.rs:4:14: 4:51 error: cannot determine a type for this bounded type parameter: unconstrained type
bar.rs:4     let _xs = Counter::new(0, 1).take(20).to_vec();
                       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The definitions of TakeIterator and TakeWhileIterator are similar, but TakeIterator is only parameterized by T (the type of the contained Iterator) while TakeWhileIterator also has an A parameter (the type of the yielded element).

It seems the type of the element A is unable to be inferred from T, where T is an Iterator<A>.

/// An iterator which only iterates over the first `n` iterations of `iter`.
pub struct TakeIterator<T> {
    priv iter: T,
    priv n: uint
}

impl<A, T: Iterator<A>> Iterator<A> for TakeIterator<T> {
    #[inline]
    fn next(&mut self) -> Option<A> {
        let next = self.iter.next();
        if self.n != 0 {
            self.n -= 1;
            next
        } else {
            None
        }
    }
}

Activity

  1. thestinger commented on Jun 6, 2013

    @thestinger
    ContributorAuthor

    #6968 is a working hack to avoid this issue, but we should fix the underlying cause.

  2. Aatch commented on Jun 23, 2013

    @Aatch
    Contributor

    I have also hit this problem, but in my case, I end up needing to use four dummy type parameters and still needed to provide a hint when called. This is not tenable as a usable API.

    I'm going to nominate this. I'm not sure what for, I'm thinking well-covered as this limits how complex you can feasibly make your types (not very, it turns out).

  3. added a commit that references this issue on Apr 8, 2021
    75d73e9
  4. added a commit that references this issue on Aug 21, 2026
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

    A-frontendArea: Compiler frontend (errors, parsing and HIR)A-type-systemArea: Type system

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions