Pattern matching: ocaml list -> Rust vec

  1. I am converting some OCaml code to Rust.

  2. I am representing OCaml list as a Rust Vec (with end = front of list).

  3. I see OCaml patterns like:

f(nil) -> ...
f(a :: nil) -> ...
f(a :: b) -> ...

Is there a nice way to match this in Rust ? Rust match works well for destructuring enums, but I want to use a Vec instead of mimicking OCaml lists via

pub enum FakeList<T> {
  Cons(T, Rc<FakeList<T>>)

EDIT: don't want -> want; i.e. I want to use Vec, I don't want to mimic FakeList

1 Like

You can use slice patterns to pattern-match on slices, but you can't use patterns to destructure a Vec by ownership.

match slice {
    [] => todo!(),
    [a] => todo!(),
    [a, b @ ..] => todo!(),

Ooh, I wrote an article which shows how to do exactly this!


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.