Debian Codegraph @

.cargo/vendor/wasm-bindgen/guide/src/reference/attributes/on-js-imports/variadic.md

raw
1 # Variadic Parameters
2
3 In javascript, both the types of function arguments, and the number of function arguments are
4 dynamic. For example
5
6 ```js
7 function sum(...rest) {
8 let i;
9 // the old way
10 let old_way = 0;
11 for (i=0; i<arguments.length; i++) {
12 old_way += arguments[i];
13 }
14 // the new way
15 let new_way = 0;
16 for (i=0; i<rest.length; i++) {
17 new_way += rest[i];
18 }
19 // both give the same answer
20 assert(old_way === new_way);
21 return new_way;
22 }
23 ```
24
25 This function doesn't translate directly into rust, since we don't currently support variadic
26 arguments on the wasm target. To bind to it, we use a slice as the last argument, and annotate the
27 function as variadic:
28
29 ```rust
30 #[wasm_bindgen]
31 extern "C" {
32 #[wasm_bindgen(variadic)]
33 fn sum(args: &[i32]) -> i32;
34 }
35 ```
36
37 when we call this function, the last argument will be expanded as the javascript expects.
38
39
40 To export a rust function to javascript with a variadic argument, we will use the same bindgen variadic attribute and assume that the last argument will be the variadic array. For example the following rust function:
41
42 ```rust
43 #[wasm_bindgen(variadic)]
44 pub fn variadic_function(arr: &JsValue) -> JsValue {
45 arr.into()
46 }
47 ```
48
49 will generate the following TS interface
50
51 ```ts
52 export function variadic_function(...arr: any): any;
53 ```