当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Rust Extend用法及代码示例


本文简要介绍rust语言中 Trait core::iter::Extend 的用法。

用法

pub trait Extend<A> {
    fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T);

    fn extend_one(&mut self, item: A) { ... }
    fn extend_reserve(&mut self, additional: usize) { ... }
}

使用迭代器的内容扩展集合。

迭代器产生一系列值,集合也可以被认为是一系列值。 Extend trait 弥补了这一差距,允许您通过包含该迭代器的内容来扩展集合。当使用已经存在的键扩展集合时,会更新该条目,或者在允许具有相同键的多个条目的集合的情况下,插入该条目。

例子

基本用法:

// You can extend a String with some chars:
let mut message = String::from("The first three letters are: ");

message.extend(&['a', 'b', 'c']);

assert_eq!("abc", &message[29..32]);

实施 Extend

// A sample collection, that's just a wrapper over Vec<T>
#[derive(Debug)]
struct MyCollection(Vec<i32>);

// Let's give it some methods so we can create one and add things
// to it.
impl MyCollection {
    fn new() -> MyCollection {
        MyCollection(Vec::new())
    }

    fn add(&mut self, elem: i32) {
        self.0.push(elem);
    }
}

// since MyCollection has a list of i32s, we implement Extend for i32
impl Extend<i32> for MyCollection {

    // This is a bit simpler with the concrete type signature: we can call
    // extend on anything which can be turned into an Iterator which gives
    // us i32s. Because we need i32s to put into MyCollection.
    fn extend<T: IntoIterator<Item=i32>>(&mut self, iter: T) {

        // The implementation is very straightforward: loop through the
        // iterator, and add() each element to ourselves.
        for elem in iter {
            self.add(elem);
        }
    }
}

let mut c = MyCollection::new();

c.add(5);
c.add(6);
c.add(7);

// let's extend our collection with three more numbers
c.extend(vec![1, 2, 3]);

// we've added these elements onto the end
assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c));

相关用法


注:本文由纯净天空筛选整理自rust-lang.org大神的英文原创作品 Trait core::iter::Extend。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。