FAQ - Help and questions

How do null, undefined, optional chaining and the nullish operator map to Rust Option?

#porting#javascript#optionpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Optional values become Option, optional chaining becomes and_then or the question mark operator on Option, and the nullish operator becomes unwrap_or. Rust has no truthy or falsy values, so the JavaScript bug where zero is replaced by a default with the or operator cannot occur.

Checked with rustc 1.93.0, Node.js v22.19.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

JavaScript has two "no value" values (null and undefined), a missing property that reads as undefined, and a notion of truthiness that treats 0, "", NaN and null as false. Rust has none of these: a value that may be absent has the type Option<T>, which is either Some(value) or None, and a condition must be a bool.

JavaScriptRust
u.address?.cityand_then on the Option (see the example below), or ? inside a function that returns Option
x ?? 3x.unwrap_or(3)
x followed by the logical-or operator and 3 (also replaces 0 and "")no equivalent: write the check you mean, such as if x == 0 { 3 } else { x }
if (x) on a number or stringif x != 0, if !s.is_empty(), or if let Some(v) = x
obj.key === undefinedmap.get("key").is_none()
if (v == null) throw new Error(...)let v = v.ok_or(error)?;

Node.js (v22.19.0) first:

javascript
const a = { address: { city: "Pune" }, retries: 0 };
const b = {};
for (const u of [a, b]) {
  const city = u.address?.city ?? "unknown";
  console.log(city, u.retries ?? 3, u.retries || 3);
}
console.log([] ? "truthy" : "falsy", "" ? "truthy" : "falsy", 0 ? "truthy" : "falsy");
text
Pune 0 3
unknown 3 3
truthy falsy falsy

Look at the first line: for a, retries is 0. u.retries ?? 3 keeps the 0; u.retries || 3 replaces it with 3, which is a classic bug that is often a feature by accident. The Rust port has to say which one it means:

src/main.rsrust
#[derive(Debug)]
struct Address { city: Option<String> }
#[derive(Debug)]
struct User { address: Option<Address>, retries: Option<u32> }

fn main() {
    let a = User { address: Some(Address { city: Some("Pune".into()) }), retries: Some(0) };
    let b = User { address: None, retries: None };
    for u in [&a, &b] {
        // JS:  u.address?.city ?? "unknown"
        let city = u.address.as_ref().and_then(|a| a.city.as_deref()).unwrap_or("unknown");
        // JS:  u.retries ?? 3      (0 is kept)      u.retries || 3  would turn 0 into 3
        let retries = u.retries.unwrap_or(3);
        println!("{city} {retries}");
    }
    // there is no "falsy": a number is not a condition
    let n = 0;
    println!("{}", if n != 0 { "truthy" } else { "zero" });
    println!("{:?}", "".is_empty());
}
text
Pune 0
unknown 3
zero
true

Some(0).unwrap_or(3) is 0, matching ??. Writing a condition like if n { ... } with an integer does not compile, so the "empty means false" bug cannot be ported by accident.

How to do it#

  1. For each variable, property or parameter that can be null or undefined, make it Option<T>. A property that is always present is a plain T.
  2. Replace a?.b?.c with a chain of and_then (or map, when the step cannot fail), or write a small function returning Option<T> and use ? inside it.
  3. Replace x ?? d with unwrap_or(d), or unwrap_or_else(|| ...) when the default is expensive to build.
  4. Replace || defaults and truthiness tests with explicit comparisons, and decide for each whether 0 and "" should count as missing.
  5. For JSON, let serde do it: Option<T> fields accept both a missing key and null (see the thread on TypeScript types and serde).

Common mistakes#

  • Using unwrap() on an Option as the translation of !. If the value is None the program panics.
  • Mixing "missing" and "empty". Option<String> (absent) and String::new() (present but empty) are different; JavaScript often treats them the same.
  • Writing Option<Option<T>> to model both null and undefined. Decide what the difference means in your data first.

Is Option slower than a null pointer?#

For references and Box, Option<Box<T>> is the same size as a plain pointer, because the compiler uses the null value for None (shown in the thread on C structs). This thread did not measure speed.

What replaces typeof x === "undefined" for a variable?#

Nothing: a variable that exists has a value. The question belongs to the type, Option or not.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet