Hey,

I’m not sure how people feel about Option types but there seem to be a few 
hundred uses in the rust codebase. Wanted to share an idea we use in our custom 
type system (“Hack”) at Facebook to make it a bit nicer to safely deal with 
null references. We don’t use Option types directly. I don’t think this adds 
any theoretical power or new possible efficiency gains, it’s mostly for making 
the code a bit simpler.

Type declarations prefixed with a question mark represent references which 
might be null. So ‘?Foo' is somewhat like a shorthand for 'Option<Foo>’.

function demo(?Car $maybe_car, Car $car) {…}

We use these like possibly-null pointers. Usually you write an if statement 
prior to using a value.

function demo(?Car $maybe_car, Car $car) {
  $car->start();
  if($maybe_car) { $maybe_car->start(); }
}

Sometimes we use these in combination with a special function “invariant", an 
assertion function that throws an exception if a condition is not met:

function demo(?Car $car) {
  invariant($car, ‘Expected non-null car for the demo’);
  $car->start();
}

If you forget to check for null one way or the other, the type-checker 
complains. This is a static, ahead-of-time check.

function demo(?Car $car) {
  $car->start(); // error
}

There are some natural annoying edge cases to be covered.

class Smash {
  private ?Car $car;

  function demo() {
    if ($this->car) {
      $this->smashCar();
      $this->car->start(); // error
    }
  }
}

A downside of this approach vs. Option is that code written using pattern 
matching over Option is more easily upgraded to code using pattern matching 
over Result (or something else).

Anyway, we like this feature and I’d be happy to see it adopted elsewhere. 
Tossing it out there as I don’t know anything about the Rust compiler or how 
language design decisions get made for it :)

-Aran
_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to