You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在自定义类Itertools库中重命名Rust Iterator的scan函数?

解决Rust中重命名std::iter::Iterator::scan的问题

你遇到的核心问题是标准库Scan迭代器的new关联函数为私有方法,外部无法直接调用。要实现重命名scan的需求,有两种惯用方法:

方法一:直接复用标准库的scan方法

标准库的Iterator::scan本身是公开方法,你可以在自定义扩展 trait 里直接调用它,无需手动调用私有构造函数,就能返回原有的Scan迭代器:

use std::iter::Scan;

trait IteratorExt: Iterator {
    fn scan_while<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
    where
        Self: Sized,
        F: FnMut(&mut St, Self::Item) -> Option<B>,
    {
        self.scan(initial_state, f)
    }
}

// 为所有实现Iterator的类型自动扩展该方法
impl<I: Iterator> IteratorExt for I {}

方法二:自定义独立迭代器结构体

如果想完全脱离标准库Scan类型的约束,你可以自己实现一个迭代器结构体,复刻scan的核心逻辑:

struct ScanWhile<I, St, F> {
    iter: I,
    state: St,
    f: F,
}

impl<I, St, F> ScanWhile<I, St, F> {
    fn new(iter: I, state: St, f: F) -> Self {
        Self { iter, state, f }
    }
}

impl<I, St, B, F> Iterator for ScanWhile<I, St, F>
where
    I: Iterator,
    F: FnMut(&mut St, I::Item) -> Option<B>,
{
    type Item = B;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            match self.iter.next() {
                Some(item) => match (self.f)(&mut self.state, item) {
                    Some(b) => return Some(b),
                    None => continue,
                },
                None => return None,
            }
        }
    }
}

// 扩展Iterator trait
trait IteratorExt: Iterator {
    fn scan_while<St, B, F>(self, initial_state: St, f: F) -> ScanWhile<Self, St, F>
    where
        Self: Sized,
        F: FnMut(&mut St, Self::Item) -> Option<B>,
    {
        ScanWhile::new(self, initial_state, f)
    }
}

impl<I: Iterator> IteratorExt for I {}

第一种方法简洁高效,直接复用标准库经过优化的实现;第二种方法更灵活,方便后续对迭代逻辑做自定义修改。

内容的提问来源于stack exchange,提问作者arkethos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 04:00:27