Part II — JavaScript Interop
local graph
Part II — JavaScript Interop
Section titled “Part II — JavaScript Interop”Part II • JavaScript Interop
Section titled “Part II • JavaScript Interop”4.1: Attribute Macros & Exposed APIs
Section titled “4.1: Attribute Macros & Exposed APIs”Attribute macros are a way to expose JavaScript functions to JavaScript code. They allow you to define functions that can be called from JavaScript, and they provide a way to manage the lifecycle of these functions.
Exposed APIs
Section titled “Exposed APIs”Exposed APIs are functions that are exposed to JavaScript through attribute macros. These functions can be called from JavaScript and can perform various tasks such as reading and writing data, performing calculations, and more.
Example
Section titled “Example”#[js_namespace]mod my_module { #[js_function] pub fn add(a: f64, b: f64) -> f64 { a + b }}In this example, the add function is exposed to JavaScript through the js_function attribute macro. The function takes two floating-point numbers as arguments and returns their sum.
Benefits
Section titled “Benefits”- Ease of Use: Attribute macros make it easy to expose Rust functions to JavaScript.
- Type Safety: The functions are type-safe, ensuring that the correct arguments are passed.
- Performance: Attribute macros provide high-performance access to Rust functions from JavaScript.
Conclusion
Section titled “Conclusion”Attribute macros and exposed APIs are powerful tools for integrating Rust with JavaScript. They allow you to create efficient and type-safe interfaces between the two languages.