Quantcast
Channel: ReScript Forum - Latest posts
Viewing all articles
Browse latest Browse all 2592

Syntax for unwrapping Option inside function

$
0
0

It is inherited from OCaml like any other grammars. I can’t find the documentation, basically destructuring in ReScript/Rust is another form of the pattern matching.

It is useful when dealing with variants that share the same data structure.

type event
  | Created({ date: Date.t, name: string, email: string })
  | Deactivited({ date: Date.t, by: option<adminId> })

// As long as you can
switch event {
| Created({ date }) | Deactivated({ date }) =>
  // `date` binding available here
}

// you can also this in the same place
let Created({ date }) | Deactivate({ date }) = event

However, unlike the switch, let patterns in ReScript/OCaml don’t handle patterns with different structures.

Rust expand this with the let-else binding

This is very useful when combined with early return. It can eliminate multiple nested switchs for destructuring.

https://rust-lang.github.io/rfcs/3137-let-else.html

The ? for Result is simply syntax sugar for pattern matching and early return through Rust’s trait specialization.


Viewing all articles
Browse latest Browse all 2592

Trending Articles