简体   繁体   English

将对元组的引用迭代器解压缩为两个引用集合

[英]Unzip iterator of references to tuples into two collections of references

I have an Iterator<Item = &(T, U)> over a slice &[(T, U)] . 我在切片&[(T, U)]有一个Iterator<Item = &(T, U)> I'd like to unzip this iterator into its components (ie obtain (Vec<&T>, Vec<&U>) ). 我想将此迭代器解压缩到其组件中(即,获取(Vec<&T>, Vec<&U>) )。

Rust provides unzip functionality through the .unzip() method on Interator : 锈通过提供解压功能.unzip()上的方法Interator

points.iter().unzip()

Unfortunately, this doesn't work as-is because .unzip() expects the type of the iterator's item to be a tuple; 不幸的是,这不能按.unzip()工作,因为.unzip()期望迭代器的项的类型为元组。 mine is a reference to a tuple. 我的是对元组的引用。

To fix this, I tried to write a function which converts between a reference to a tuple and a tuple of references: 为了解决这个问题,我尝试编写一个函数,该函数在对元组的引用和对引用的元组之间进行转换:

fn distribute_ref<'a, T, U>(x: &'a (T, U)) -> (&'a T, &'a U) {
    (&x.0, &x.1)
}

I can then map over the resulting iterator to get something .unzip() can handle: 然后,我可以map到生成的迭代器上,以获取.unzip()可以处理的内容:

points.iter().map(distribute_ref).unzip()

This works now, but I this feels a bit strange. 现在可以使用,但是我有点奇怪。 In particular, distribute_ref seems like a fairly simple operation that would be provided by the Rust standard library. 特别是,Rust标准库提供的distribute_ref似乎是一个相当简单的操作。 I'm guessing it either is and I can't find it, or I'm not approaching this the right way. 我猜它是或者我找不到它,或者我没有以正确的方式接近它。

Is there a better way to do this? 有一个更好的方法吗?

Is there a better way to do this? 有一个更好的方法吗?

"Better" is a bit subjective. “更好”有点主观。 You can make your function shorter: 您可以使函数更短:

fn distribute_ref<T, U>(x: &(T, U)) -> (&T, &U) {
    (&x.0, &x.1)
}

Lifetime elision allows to omit lifetime annotations in this case. 终身省音允许省略一生的注释在这种情况下。

You can use a closure to do the same thing: 您可以使用闭包执行相同的操作:

points.iter().map(|&(ref a, ref b)| (a, b)).unzip()

Depending on the task it can be sufficient to clone the data. 根据任务,克隆数据就足够了。 Especially in this case, as reference to u8 takes 4 or 8 times more space than u8 itself. 特别是在这种情况下,引用u8占用的空间是u8本身的4或8倍。

points().iter().cloned().unzip()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM