mirror of
https://github.com/fluencelabs/wasm-bindgen
synced 2025-06-23 17:51:33 +00:00
Add docs and remove typecheck from variadic attribute
This commit is contained in:
38
guide/src/reference/attributes/on-js-imports/variadic.md
Normal file
38
guide/src/reference/attributes/on-js-imports/variadic.md
Normal file
@ -0,0 +1,38 @@
|
||||
# Variadic Parameters
|
||||
|
||||
In javascript, both the types of function arguments, and the number of function arguments are
|
||||
dynamic. For example
|
||||
|
||||
```js
|
||||
function sum(...rest) {
|
||||
let i;
|
||||
// the old way
|
||||
let old_way = 0;
|
||||
for (i=0; i<arguments.length; i++) {
|
||||
old_way += arguments[i];
|
||||
}
|
||||
// the new way
|
||||
let new_way = 0;
|
||||
for (i=0; i<rest.length; i++) {
|
||||
new_way += rest[i];
|
||||
}
|
||||
// both give the same answer
|
||||
assert(old_way === new_way);
|
||||
return new_way;
|
||||
}
|
||||
```
|
||||
|
||||
This function doesn't translate directly into rust, since we don't currently support variadic
|
||||
arguments on the wasm target. To bind to it, we use a slice as the last argument, and annotate the
|
||||
function as variadic:
|
||||
|
||||
```rust
|
||||
#[wasm_bindgen]
|
||||
extern {
|
||||
#[wasm_bindgen(variadic)]
|
||||
fn sum(args: &[i32]) -> i32;
|
||||
}
|
||||
```
|
||||
|
||||
when we call this function, the last argument will be expanded as the javascript expects.
|
||||
|
Reference in New Issue
Block a user