如何从 .map() 输出多个值或在一次迭代中使用 map 两次?

Ded*_*mer 2 iterator functional-programming rust

如何在一个 into_iter 上使用两次 map ?目前我有。

let res_arr_to: Vec<String> = v.result.transactions.into_iter().map( |x| x.to).collect();
let res_arr_from: Vec<String> = v.result.transactions.into_iter().map( |x| x.from).collect();
Run Code Online (Sandbox Code Playgroud)

我想要的是两个数组都在一个数组中,顺序并不重要。我需要一个输出两个值的闭包(如果这甚至是一个闭包?)。或者一种在一次迭代中使用 map 两次的方法,而不使用生成的值,而是使用未触及的迭代器(如果有意义并且可能的话)。我在函数式编程方面完全是菜鸟,所以如果有一种完全不同的方法来做到这一点,另一个解释就可以了。

v 是 EthBlockTxResponse:

#[derive(Debug, Deserialize)]
struct EthTransactionObj {
    from: String,
    to: String

}

#[derive(Debug, Deserialize)]
struct EthTransactions {
    transactions : Vec<EthTransactionObj>
}

#[derive(Debug, Deserialize)]
struct EthBlockTxResponse {
    result : EthTransactions
}
Run Code Online (Sandbox Code Playgroud)

谢谢

cre*_*ion 7

您可以使用.unzip()一次收集两个向量,如下所示:

let (res_arr_to, res_arr_from): (Vec<_>, Vec<_>) = 
    v.result.transactions.into_iter().map(|x| (x.to, x.from)).unzip();
Run Code Online (Sandbox Code Playgroud)

请注意,into_iter 消耗v.result.transactions- 移出该字段。这可能不是您想要的,在这种情况下您应该复制字符串:

let (res_arr_to, res_arr_from): (Vec<_>, Vec<_>) = 
    v.result.transactions.iter().map(|x| (x.to.clone(), x.from.clone())).unzip();
Run Code Online (Sandbox Code Playgroud)