Box<[T]> and Vec<T>
T parameter | &T parameter | &mut T parameter | T return value | Option<T> parameter | Option<T> return value | JavaScript representation |
|---|---|---|---|---|---|---|
| Yes | No | No | Yes | Yes | Yes | A JavaScript Array object |
You can pass boxed slices and Vecs of several different types to and from JS:
JsValues.- Imported JavaScript types.
- Exported Rust types.
- C-style exported enums and string enums.
Strings.bools andchars.&strs, to JS only.
Imported JS types and JsValues are passed as their handles. bools,
chars, C-style and string enums, and &strs are converted element by
element, the same way a single value of that type is. Strings and
exported Rust types are passed as JS values, and each is checked as it
comes into Rust, so an element of the wrong type throws.
Borrowed slices (&[T]) of the same element types, apart from exported Rust
types, can be passed to imported JS functions; see
slice and vec.
You can also pass boxed slices of numbers to JS,
except that they’re converted to typed arrays (Uint8Array, Int32Array, etc.)
instead of regular arrays.
Example Rust Usage
#![allow(unused)]
fn main() {
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn take_boxed_js_value_slice_by_value(x: Box<[JsValue]>) {}
#[wasm_bindgen]
pub fn return_boxed_js_value_slice() -> Box<[JsValue]> {
vec![JsValue::NULL, JsValue::UNDEFINED].into_boxed_slice()
}
#[wasm_bindgen]
pub fn take_option_boxed_js_value_slice(x: Option<Box<[JsValue]>>) {}
#[wasm_bindgen]
pub fn return_option_boxed_js_value_slice() -> Option<Box<[JsValue]>> {
None
}
}
Example JavaScript Usage
import {
take_boxed_js_value_slice_by_value,
return_boxed_js_value_slice,
take_option_boxed_js_value_slice,
return_option_boxed_js_value_slice,
} from './guide_supported_types_examples';
take_boxed_js_value_slice_by_value([null, true, 2, {}, []]);
let values = return_boxed_js_value_slice();
console.log(values instanceof Array); // true
take_option_boxed_js_value_slice(null);
take_option_boxed_js_value_slice(undefined);
take_option_boxed_js_value_slice([1, 2, 3]);
let maybeValues = return_option_boxed_js_value_slice();
if (maybeValues == null) {
// ...
} else {
console.log(maybeValues instanceof Array); // true
}