當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。