Rust: Understanding 'match &self' for Pattern Matching
The 'match &self' syntax in Rust is used for pattern matching on a reference to 'self', which is a reference to the current instance of a struct or enum. It allows the implementation of different behavior depending on the state of the instance.
Here's an example of how 'match &self' can be used in a struct:
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn is_square(&self) -> bool {
match &self {
Rectangle { width, height } if width == height => true,
_ => false,
}
}
}
fn main() {
let rect = Rectangle { width: 10, height: 20 };
println!("Area of rectangle: {}", rect.area());
println!("Is rectangle a square? {}", rect.is_square());
}
In this example, the 'is_square' method uses 'match &self' to check whether the rectangle is a square or not. If the width and height are equal, it returns true, otherwise it returns false.
Note that the '&' symbol in '&self' means that the method takes a reference to 'self' instead of taking ownership of the instance. This is because the method only needs to read the values of the instance, not modify it.
原文地址: https://www.cveoy.top/t/topic/l6CW 著作权归作者所有。请勿转载和采集!