Skip to main content

Iterable

Trait Iterable 

Source
pub trait Iterable {
    type Item;
}
Expand description

Trait for JavaScript types that implement the iterable protocol via Symbol.iterator.

Types implementing this trait can be iterated over using JavaScript’s iteration protocol. The Item associated type specifies the type of values yielded.

§Built-in Iterables

Many js-sys collection types implement Iterable out of the box:

use js_sys::{Array, Map, Set};

// Array<T> yields T
let arr: Array<Number> = get_numbers();
for value in arr.iter() {
    let num: Number = value?;
}

// Map<K, V> yields Array (key-value pairs)
let map: Map<JsString, Number> = get_map();
for entry in map.iter() {
    let pair: Array = entry?;
}

// Set<T> yields T
let set: Set<JsString> = get_set();
for value in set.iter() {
    let s: JsString = value?;
}

§Typing Foreign Iterators

If you have a JavaScript value that implements the iterator protocol (has a next() method) but isn’t a built-in type, you can use JsCast to cast it to Iterator<T>:

use js_sys::Iterator;
use wasm_bindgen::JsCast;

// For a value you know implements the iterator protocol
fn process_iterator(js_iter: JsValue) {
    // Checked cast - returns None if not an iterator
    if let Some(iter) = js_iter.dyn_ref::<Iterator<Number>>() {
        for value in iter.into_iter() {
            let num: Number = value.unwrap();
            // ...
        }
    }
}

// Or with unchecked cast when you're certain of the type
fn process_known_iterator(js_iter: JsValue) {
    let iter: &Iterator<JsString> = js_iter.unchecked_ref();
    for value in iter.into_iter() {
        let s: JsString = value.unwrap();
        // ...
    }
}

§Using with JsValue

For dynamic or unknown iterables, use try_iter which returns an untyped iterator:

fn iterate_unknown(val: &JsValue) -> Result<(), JsValue> {
    if let Some(iter) = js_sys::try_iter(val)? {
        for item in iter {
            let value: JsValue = item?;
            // Handle dynamically...
        }
    }
    Ok(())
}

Required Associated Types§

Source

type Item

The type of values yielded by this iterable.

Implementations on Foreign Types§

Source§

impl<T: Iterable> Iterable for &T

Source§

type Item = <T as Iterable>::Item

Implementors§