Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Matching on a reference to an enum... issues arising for newbies #46208

Closed
Bellarmine-Head opened this issue Nov 23, 2017 · 3 comments
Closed

Comments

@Bellarmine-Head
Copy link

A few issues raised by this SO question, certainly for a newbie like me.

  1. As the OP says: "It seems like every introductory document for Rust's enum types explains how to match on an enum object that you own. But what if you do not own the enum object and you just have a reference to it that you want to match against?" Well, quite! This had me scratching my head for while, and led me to this SO question.

  2. Does the syntax have to be different? Can the compiler help here?

  3. What I've found and noted on SO is that the idiomatic answer causes an error pertaining to a missing ref in one of the arms to be placed on the line containing the match keyword. This isn't helpful as it doesn't identify the errant arm. The unaccepted and presumably non-idiomatic answer:-

match self {
    &Animal::Cat(ref c) => f.write_str("c"),
    &Animal::Dog => f.write_str("d"),
}

is better because if the ref is omitted from the Cat arm, the compiler will put the error on that arm.

@vitalyd
Copy link

vitalyd commented Nov 23, 2017

rust-lang/rust-roadmap-2017#24 should make this newbie friendly.

@sinkuu
Copy link
Contributor

sinkuu commented Nov 23, 2017

What I've found and noted on SO is that the idiomatic answer causes an error pertaining to a missing ref in one of the arms to be placed on the line containing the match keyword.

Error span is on match's line, but the arm missing ref seems to be pointed out in "hint" (a - is underlining c).

error[E0507]: cannot move out of borrowed content
  --> src/main.rs:11:15
   |
11 |         match *self {
   |               ^^^^^ cannot move out of borrowed content
12 |             Animal::Cat(c) => f.write_str("c"),
   |                         - hint: to prevent move, use `ref c` or `ref mut c`

@Bellarmine-Head
Copy link
Author

@sinkuu, that's true and thanks for pointing that out. That hint wasn't apparent when I saw the error in Visual Studio Code, as reported by the RLS. So it's a good thing to run cargo build to look at the more detailed error, but I still reckon that the

match self {
    &Animal::Cat(ref c) => f.write_str("c"),
    &Animal::Dog => f.write_str("d"),
}

syntax is more helpful right now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants