另一个基本的Rust问题:有人可以举例说明使用from_iter创建BTreeSet吗?
据推测,BTreeSet确实实现了FromIterator特性,但最有用的形式是:
let triangles = range(1, top).map(|x| x*(x+1)/2);
let bset: BTreeSet<uint> = BTreeSet::from_iter(triangles);
给出错误:
.../src/main.rs:28:32: 28:51 error: unresolved name `BTreeSet::from_iter`. .../src/main.rs:28
let bset: BTreeSet<uint> = BTreeSet::from_iter(triangles);
好的,这是一个特性,所以应该是一个对象方法:
let triangles = range(1, top).map(|x| x*(x+1)/2);
let bset: BTreeSet<uint> = BTreeSet::new();
return bset.from_iter(triangles);
但这会出错:
.../src/main.rs:29:17: 29:37 error: type `collections::btree::set::BTreeSet<uint>` does not implement any method in scope named `from_iter`
.../src/main.rs:29 return bset.from_iter(triangles);
^~~~~~~~~~~~~~~~~~~~
.../src/main.rs:29:37: 29:37 note: found defined static methods, maybe a `self` is missing?
.../src/main.rs:29:17: 29:37 note: candidate #1 is defined in the trait `core::iter::FromIterator`
.../src/main.rs:29 return bset.from_iter(triangles);
那么,使用它的正确方法是什么?
答案 0 :(得分:4)
看起来需要使用特征名称进行限定:
let bset: BTreeSet<uint> = FromIterator::from_iter(triangles);
但我认为使用.collect()更加惯用:
let bset: BTreeSet<uint> = range(1, 10).map(|x| x*(x+1)/2).collect();