乐闻世界logo
搜索文章和话题

What is the purpose of the '@' symbol in Rust?

2024年7月17日 22:11

In Rust, the @ symbol is primarily used within pattern matching contexts. It enables you to bind the matched value to a variable during pattern matching. This allows you not only to verify if the value matches a specific pattern but also to reuse it later in your code.

rust
let value = Some(5); match value { Some(x) @ Some(5) => println!("Got an Some with 5, and x is {:?}, x), _ => (), }

In this example, we use @ to bind the value matched by Some(5) to the variable x, enabling you to utilize x within the println! macro.

标签:Rust