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

What does the '@' symbol do in Rust?

1个答案

1

In Rust, the @ symbol is used as part of pattern binding, allowing you to bind the value to a variable during pattern matching. It's a convenient way to combine pattern matching with binding.

For example, suppose we have an enum type representing various vehicle types, along with their specific models:

rust
enum Vehicle { Car(String), Bicycle(String), Scooter(String), } fn main() { let my_vehicle = Vehicle::Car("Toyota".to_string()); match my_vehicle { Vehicle::Car(model @ "Toyota") => println!("It's a Toyota car, model {}", model), Vehicle::Car(model) => println!("It's some other car, model {}", model), _ => println!("It's not a car"), } }

In this example, our match statement not only checks if my_vehicle is of type Vehicle::Car, but also verifies whether the vehicle model is "Toyota". If the model matches "Toyota", it binds the value "Toyota" to the variable model and then uses it within the println! macro.

Using the @ in pattern matching is highly useful because it enables you to directly access and utilize values meeting specific conditions while performing pattern matching.

2024年7月17日 19:40 回复

你的答案