rust持续学习 iterator

他是一个trait
需要实现next方法给他
大概这样的

pub trait Iterator {
    type Item;

    fn next(&mut self) -> Option<Self::Item>;
}

网上找来一段对Chars的实现里

#[derive(Clone)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Chars<'a> {
    pub(super) iter: slice::Iter<'a, u8>,
}

impl<'a> Iterator for Chars<'a> {
     type Item = char;#[inline]
     fn next(&mut self) -> Option<char> {
         next_code_point(&mut self.iter).map(|ch| {
             // SAFETY: `str` invariant says `ch` is a valid Unicode Scalar Value.
             unsafe { char::from_u32_unchecked(ch) }
         })
     }
 }

会调这个看起来就是访问下一个字符,咋去到下一个的呢这个slice::Iter struct内部是有ptr,end俩成员的
他会实现IntoIterator 这个trait的,然后这个IntoIter的next实现的最下面的else指针地址+1。

#[stable(feature = "rust1", since = "1.0.0")]
impl<T, A: Allocator> Iterator for IntoIter<T, A> {
    type Item = T;

    #[inline]
    fn next(&mut self) -> Option<T> {
        if self.ptr == self.end {
            None
        } else if T::IS_ZST {
            // `ptr` has to stay where it is to remain aligned, so we reduce the length by 1 by
            // reducing the `end`.
            self.end = self.end.wrapping_byte_sub(1);

            // Make up a value of this ZST.
            Some(unsafe { mem::zeroed() })
        } else {
            let old = self.ptr;
            self.ptr = unsafe { self.ptr.add(1) };

            Some(unsafe { ptr::read(old) })
        }
    }

然后这个要some.into_iter().map(xxx).collect比较常见
如果直接some.into_iter().sum()这种函数所有权会直接无了

你可能感兴趣的:(rust,学习)