Collect() method implementation of IntoIter structure

⚓ Rust    📅 2025-06-21    👤 surdeus    👁️ 6      

surdeus

Warning

This post was published 53 days ago. The information described in this article may have changed.

I was looking at how the collect method is implemented for the IntoIter structure.

    fn collect<B: FromIterator<Self::Item>>(self) -> B
    where
        Self: Sized,
    {
        // This is too aggressive to turn on for everything all the time, but PR#137908
        // accidentally noticed that some rustc iterators had malformed `size_hint`s,
        // so this will help catch such things in debug-assertions-std runners,
        // even if users won't actually ever see it.
        if cfg!(debug_assertions) {
            let hint = self.size_hint();
            assert!(hint.1.is_none_or(|high| high >= hint.0), "Malformed size_hint {hint:?}");
        }

        FromIterator::from_iter(self)
    }

I have a couple of questions -

  1. What does Self::Item represent here? Does it mean IntoIter::Item or <IntoIter as Iterator>::Item ?.
  2. How is this code able to call from_iter() like this? Why does it not need call syntax as <B as FromIterator>::from_iter(self)?

I wrote some sample code to mimic collect()'s call semantics and compiler complains that I have to use fully qualified path like <struct as trait>::method(). But in here, compiler is fine. Why?

Thanks!

2 posts - 2 participants

Read full topic

🏷️ rust_feed