What does the '@' symbol do in Rust?

2019-07-06 21:51发布

问题:

I forgot to specify the type of a parameter and the error message was as follows:

error: expected one of `:` or `@`, found `)`
 --> src/main.rs:2:12
  |
2 | fn func(arg)
  |            ^ expected one of `:` or `@` here

Which raises the question: what can you do with an @ symbol? I don't remember reading about using the @ symbol for anything. I also did some Googling and couldn't find anything. What does @ do?

回答1:

You can use the @ symbol to bind a pattern to a name. As the Rust Reference demonstrates:

let x = 1;

match x {
    e @ 1 ... 5 => println!("got a range element {}", e),
    _ => println!("anything"),
}

Assignments in Rust allow pattern expressions (provided they are complete) and argument lists are no exception. In the specific case of @, this isn't very useful because you can already name the matched parameter. However, for completeness, here is an example which compiles:

enum MyEnum {
    TheOnlyCase(u8),
}

fn my_fn(x @ MyEnum::TheOnlyCase(_): MyEnum) {}


标签: rust