What does the '@' symbol do in 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?

2

1 Answer

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) {}
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like