Destructuring -- matching and borrowing

I just found an interesting Github book called "Rust for C++ programmers":

I was surprised to find that on this page

I was learning things that I didn't know that I didn't know about Rust -- some subtle stuff that I had never thought about but, as it turns out, did not really grok. This kind of walk through the subtleties is very helpful and I doubt that many folks know about the book (I only found it because I am doing some Rust/C++ interop), so I thought I would share it here. It's probably a bit advanced for beginning Rust programmers, but I hope that intermediate folks will find it useful.

2 Likes

I wonder if that chapter is just really old. Today, you can match on a reference to an enum without putting an & on the enum variants. When you do that, if the matched variant has any fields, those fields automatically become references to those fields. This is called match ergonomics.

6 Likes

It also says some stuff which is currently blatantly wrong, such as:

enum Enum1 {
    Var1,
    Var2,
    Var3,
}

Enum1 has copy semantics.

This is wrong: an enum, even one without "payloads" (dubbed "C style enums"), is not Copy unless you opt into making it Copy:

+ #[derive(Clone, Copy)]
  enum Enum1 {
      Var1,
      Var2,
      Var3,
  }

The match will nonetheless work, since whether a scrutinee (the expression that is matched) is moved or not depends on the bindings / sub-variables declared in the match arms. With a C-style enum, the enums often won't feature new bindings / sub-variables, and so won't move a thing.

5 Likes

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.