[Question] Blog Post: Mixing matching, mutation, and moves in Rust


#1

I’ve just read this blog post from 2015 about enums and matches. In the conclusion there are four points which are not covered by the blog post and reader is encouraged to consult the documentation. Unfortunately I wasn’t able to find much information about those topics in it.

Thus I would like to ask here about these points.


  • how to say Higher instead of Answer::Higher in a pattern

If I understand this right, it is possible to omit the enum name in the matching block. So this example

enum MyEnum {A, B}

match e {
    MyEnum::A => "A",
    MyEnum::B => "B"
}

could be become something like this:

match e {
    A => "A",
    B => "B"
}

  • defining new named constants

What is meant by this?


  • binding via ident @ pattern

Where is the advantage using @ instead of the matched value itself?

let x = 1;

match x {
    e @ 1 ... 5 => println!("got a range element {}", e),
    // in comparison to
    1 ... 5 => println!("got a range element {}", x),
}

  • the potentially subtle difference between { let id = expr; ... } versus match expr { id => { ... } }

What are those subtle differences?


#3

You can write use Answer::Higher; to import the name Higher into the current namespace. You can also use a wildcard (*) to import several names at once. For example:

enum MyEnum {A, B}

use MyEnum::*;

match e {
    A => "A",
    B => "B"
}

Where is the advantage using @ instead of the matched value itself?

It’s especially useful if the @ is binding to something “inside” the pattern.

match option {
    Some(x @ 1 ... 5) => x + 1,
    _ => false
}
  • defining new named constants

See this chapter of the book: http://doc.rust-lang.org/book/const-and-static.html


#4

It seems like you’ve gotten some good answers already, so I’ll just say this: if you read a blog post before May of 2015, what you read may not be accurate. And that might be why it’s hard to find documentation.

As an example, in older, pre-1.0 Rust, there was a time where you didn’t need to use the enum name, like @mbrubeck mentions in his answer. But now you do, because enums are properly namespaced.


#5

First one can be solved by using globs: use MyEnum::* This can be done within any block, if you’re worried about namespace pollution.

I’m not sure what they mean by new named constants. Maybe someone else can expand.

Binding via ident @ pattern is useful when you need a new variable. Such as:

match foo {
    Foo(inside @ 1 ... 5) => {/* you can reference `inside` here */}
    _ => {}
}

(off topic, but sorry for the deleted post. The page randomly sent the post while I was working on it. :confused:)