What does the '@' symbol do in Rust?

时间:2018-04-18 18:18:32

标签: rust

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 个答案:

答案 0 :(得分:5)

您可以使用@符号将模式绑定到名称。正如Rust Reference demonstrates

let x = 1;

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

Rust allow pattern expressions中的分配(前提是它们已完成)和argument lists are no exception。在@的特定情况下,这不是非常有用,因为您已经可以命名匹配的参数。但是,为了完整性,这里有一个编译的例子:

enum MyEnum {
    TheOnlyCase(u8),
}

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