为所有迭代器实现特征

问题描述 投票:0回答:1

我正在创建一种方法来格式化迭代器中的数据。为了允许链接,我试图通过泛型提供它作为Iterator的新方法:

trait ToSeparatedString {
    fn to_separated_string(self, line_prefix: &str, separator: &str) -> String;
}

impl<T, I> ToSeparatedString for I
where
    T: Display,
    I: Iterator<Item = T> + Clone,
{
    fn to_separated_string(self, line_prefix: &str, separator: &str) -> String {
        let len = self.clone().count();

        self.enumerate()
            .map(|(i, line)| if i < len - 1 {
                (line, separator)
            } else {
                (line, "")
            })
            .fold::<String, _>("".to_owned(), |acc, (line, line_end)| {
                format!("{}{}{}{}", acc, line_prefix, line, line_end)
            })
    }
}

然后我在这里使用它:

#[derive(Debug)]
pub struct TransactionDocumentBuilder<'a> {
    /// Currency Id.
    pub currency: &'a str,
    /// Document timestamp.
    pub blockstamp: Blockstamp,
    /// Transaction locktime (in seconds ?)
    pub locktime: u64,
    /// List of issuers.
    pub issuers: Vec<ed25519::PublicKey>,
    /// List of inputs.
    pub inputs: Vec<Input>,
    /// List of outputs.
    pub outputs: Vec<Output>,
    /// Transaction comment.
    pub comment: &'a str,
}

impl<'a> DocumentBuilder<TransactionDocument> for TransactionDocumentBuilder<'a> {
    fn build_with_signature(self, signature: ed25519::Signature) -> TransactionDocument {
        TransactionDocument {
            document: GenericDocumentBuilder::new(10, "Transaction", self.currency)
                .with("Blockstamp", &self.blockstamp.to_string())
                .with("Locktime", &self.locktime.to_string())
                .with("Issuers", &self.issuers.iter().to_separated_string("", "\n"))
                .with("Inputs", &self.inputs.iter()
                    .map(|input| input.source)
                    .to_separated_string("", " "))
                // Iterate through each input unlocks
                .with("Unlocks", &self.inputs.iter()
                    .enumerate()
                    .map(|(i, input)| {
                        input.unlocks.iter().to_separated_string(&i.to_string(), "\n")
                    })
                    .to_separated_string("", "\n")
                )
                // more fields
                .build_with_signature(signature),
        };

        unimplemented!()
    }

    fn build_and_sign(self, _private_key: &ed25519::PrivateKey) -> TransactionDocument {
        unimplemented!()
    }
}

当我在.iter()之后使用它而不是在.map()之后使用它时它会起作用,并说它没有实现。但std::slice::Iterstd::iter::Map实施Iterator<Item = T> + Clone,那么问题出在哪里?

先谢谢你的帮助。

iterator rust traits
1个回答
1
投票

您的问题的MCVE可以写成

vec![1,2,3].iter().map(|x| x).to_separated_string("", "")

你在以下假设中错了

std::iter::Map实施Iterator<Item = T> + Clone

在Rust文档中Trait implementationsstd::iter::Map部分包括

impl<I, F> Clone for Map<I, F> where
    F: Clone,
    I: Clone, 

当源迭代器Map和函数Clone的类型都实现I时,F实现Clone

不幸的是,闭包不会在当前稳定的Rust版本1.22.1中实现Clone。该功能在夜间Rust特色门clone_closures下可用。 Playground link

您也可以通过重写Clone来删除to_separated_string的要求

fn to_separated_string(self, line_prefix: &str, separator: &str) -> String {
    self.fold((true, "".to_string()), |(first, acc), line| {
        (
            false,
            format!(
                "{}{}{}{}",
                acc,
                if first { "" } else { separator },
                line_prefix,
                line
            ),
        )
    }).1
}

Playground link

© www.soinside.com 2019 - 2024. All rights reserved.