Rust and JavaScript interoperability coming via WebAssembly

Posted on 09-04-2018 , by: admin , in , 0 Comments

Mozilla is working on a bridge between types in JavaScript and the Rust language, called wasm-bindgen, that builds on the WebAssembly portable code format.

The wasm-bindgen effort is meant to improve interoperability between JavaScript and Rust and to make Rust a web language like JavaScript, via WebAssembly. Wasm-bindgen provides high-level interactions between WebAssembly (wasm) modules and JavaScript. With wasm-bindgen, JavaScript and WebAssembly could communicate with strings, JavaScript objects, and classes as opposed to just integers and floats.

The high-level functions of wasm-bindgen include:

  • Import of JavaScript structs, functions, and objects to call in WebAssembly. Developers can call JavaScript methods on a struct and access properties, providing a native feel to Rust code once annotations are connected.
  • Export of Rust structures and functions to JavaScript. A Rust struct can be exported, which turns into a JavaScript class. Structs can then be passed around instead of just integers.

Currently, WebAssembly supports only four types: two integer types and two floating-point types. But JavaScript and Rust developers are often working with richer types, such as Rust developers working with Result for error handling. With wasm-bindgen, JavaScript could call a Rust API with a string or a Rust function to catch a JavaScript exception. By eliminating the mismatch between WebAssembly and JavaScript, JavaScript could invoke WebAssembly functions and WebAssembly could do the same with JavaScript functions.