简体   繁体   English

如果 map 不是迭代器,如何引用<item=&t> ?</item=&t>

[英]How to map to references if it's not an Iterator<Item=&T>?

I have a function that receives Iterator<Item=AsRef> and I wanted to get an array of substrings form this iterator.我有一个接收 Iterator<Item=AsRef> 的 function,我想从这个迭代器中获取一个子字符串数组。 The issue is that when mapping, .map() gets ownership of AsRef and I can't return as_ref() .问题是在映射时, .map()获得了 AsRef 的所有权,而我无法返回as_ref() How can I turn this iterator into an iterator of references like with Vec::iter?我怎样才能把这个迭代器变成像 Vec::iter 这样的引用迭代器? Sample code:示例代码:

fn a(lines: impl Iterator<Item=impl AsRef<str>>) {
    println!("{:?}", lines.map(|s| s.as_ref()).collect::<Vec<&str>>());
}

a(vec!["one".to_string(), "two".to_string()].iter());

Its a bit problematic to do with just an iterator.仅使用迭代器有点问题。 As signature describes, iterator can very match own the Item (s) and transfer the ownership to you inside the closure.正如签名所描述的,迭代器可以非常匹配拥有Item (s) 并将所有权转移给闭包内的您。 Consider taking &impl AsRef<str> instead.考虑&impl AsRef<str> This should not be a problem to provide at the caller site.在调用方站点提供这应该不是问题。

EDIT编辑

It is actually tricky on the caller side too.实际上,调用方也很棘手。 Im using a ReadBuf that returns an Iterator<Item=String>.我正在使用返回 Iterator<Item=String> 的 ReadBuf。 How would you turn this iterator into an Iterator<Item=&String>?如何将此迭代器变成 Iterator<Item=&String>?

BufRead will read lines as you demand them and it is designed to wait on the input. BufRead 将根据您的需要读取行,它被设计为等待输入。 To use it properly and with memory efficiency, I'd recommend processing each line in a loop and discarding it before reading the next.为了正确使用它并以 memory 的效率,我建议循环处理每一行并在阅读下一行之前丢弃它。

That's the solution I found but it seems very costly having to allocate an entire Vec just to get the references of items I already own in the iterator.这是我找到的解决方案,但似乎必须分配整个 Vec 才能获得迭代器中我已经拥有的项目的引用,这似乎非常昂贵。

Iterator does not in fact own all the strings at the same time. Iterator 实际上并不同时拥有所有的字符串。 Instead it reads them in batches (or it should) and it does not store them internally for you to reference them (or at least it should not).相反,它会分批读取它们(或者它应该)并且它不会在内部存储它们供您引用它们(或者至少它不应该)。

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

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