Appearance
Primitive Types
Fresh 🌱In JavaScript, the primitive types are values that aren't objects: numbers, strings, booleans, undefined, and null. This guide shows how to construct each one from Rust using the context (cx).
Numbers
cx.number() constructs a JavaScript number from any Rust number compatible with f64. That includes both integers and floating-point literals:
rust
let i: Handle<JsNumber> = cx.number(42);
let f: Handle<JsNumber> = cx.number(3.14);For types that are not implicitly convertible to f64, cast explicitly with Rust's as operator:
rust
let size: usize = std::mem::size_of::<u128>();
let n = cx.number(size as f64);Lossy casts
Casting some integer types to f64 can lose precision. When that matters, prefer the TryFrom API to detect loss instead of silently truncating.
Strings
cx.string() constructs a JavaScript string from a reference to a Rust string:
rust
let s: Handle<JsString> = cx.string("foobar");Booleans
cx.boolean() constructs a JavaScript boolean:
rust
let b: Handle<JsBoolean> = cx.boolean(true);Undefined
cx.undefined() constructs the JavaScript undefined value:
rust
let u: Handle<JsUndefined> = cx.undefined();Null
cx.null() constructs the JavaScript null value:
rust
let n: Handle<JsNull> = cx.null();At a glance
| JavaScript value | Rust constructor | Returns |
|---|---|---|
| number | cx.number(x) | Handle<JsNumber> |
| string | cx.string(s) | Handle<JsString> |
| boolean | cx.boolean(b) | Handle<JsBoolean> |
undefined | cx.undefined() | Handle<JsUndefined> |
null | cx.null() | Handle<JsNull> |
Handles
Every constructor returns a Handle<...>. A handle is a safe, lifetime-tracked reference to a value managed by the JavaScript garbage collector. You pass handles around and eventually return them or set them on objects.