我正在尝试从Vec<BTreeSet<char>>创建一个集向量( Vec<Vec<char>> )。到目前为止,我的进展如下:
use std::collections::BTreeSet;
fn main() {
// The data
let transaction_list = [
vec!['A','B','C','D'],
vec!['B','B','C'],
vec!['A','B','B','D']
];
// Successfully created a set from the Vec of Vec. It contains unique chars
let item_set: BTreeSet<char> = transaction_list.iter().flat_map(|t| t).cloned().collect();
// Made the same Vec of Vec. Basically just experimenting with map and collect
let the_same_transaction_list: Vec<Vec<char>> = transaction_list.iter().map(|t| t ).cloned().collect::<Vec<_>>();
// ERROR
let transaction_set: Vec<BTreeSet<char>> = transaction_list
.iter()
.map(|t| t.iter().map(|t| t).cloned().collect() )
.cloned().collect::<Vec<_>>();
}错误信息是:
error: the trait `core::iter::FromIterator<char>` is not implemented for the type `&_` [E0277]
.map(|t| t.iter().map(|t| t).cloned().collect() )
^~~~~~~~~
help: see the detailed explanation for E0277
note: a collection of type `&_` cannot be built from an iterator over elements of type `char`我还没有找到用Vec<BTreeSet<char>>制作Vec<Vec<char>>的正确方法。这是操场网址:http://is.gd/WVONHY。
发布于 2015-12-12 20:53:04
错误信息有点奇怪。以下是解决办法:
let transaction_set: Vec<BTreeSet<_>> =
transaction_list
.iter()
.map(|t| t.iter().cloned().collect())
.collect();这两个主要变化是:
map(|x| x)是毫无意义的。这是个禁止行动。cloned。map调用的结果类型已经是一个BTreeSet。没必要再克隆它了。后者解决了您的问题,因此让我们看看定义:
fn cloned<'a, T>(self) -> Cloned<Self>
where Self: Iterator<Item=&'a T>,
T: 'a + Clone为了能够调用cloned,迭代器Item必须是一个引用,它是可克隆的。但是,您正在尝试在BTreeSet上迭代,这不是引用。编译器选择告诉您,没有办法将collect的内部迭代器char转换为&_ (对某种类型的引用),这样就满足了调用cloned的要求。我的猜测是,内部类型比collect所需要的类型有更大的回旋余地。如果我们稍微重写原始代码,以便在内部有一个更明确的类型:
let transaction_set: Vec<_> =
transaction_list
.iter()
.map(|t| -> BTreeSet<_> {t.iter().cloned().collect()})
.cloned().collect();我们得到了一组不同的错误:
error: type mismatch resolving `<[closure...] as core::ops::FnOnce<(&collections::vec::Vec<char>,)>>::Output == &_`:
expected struct `collections::btree::set::BTreeSet`,
found &-ptr [E0271]
.cloned().collect();
^~~~~~~~
error: no method named `collect` found for type `core::iter::Cloned<core::iter::Map<core::slice::Iter<'_, collections::vec::Vec<char>>, [closure...]>>` in the current scope
.cloned().collect();
^~~~~~~~~
note: the method `collect` exists but the following trait bounds were not satisfied: `core::iter::Cloned<core::iter::Map<core::slice::Iter<'_, collections::vec::Vec<char>>, [closure...]>> : core::iter::Iterator`这有助于强调问题源于cloned的外部使用。
https://stackoverflow.com/questions/34244518
复制相似问题