rust iterate over struct fields
To iterate over the fields of a struct in Rust, you can use a for
loop and destructure the fields of the struct inside the loop. Here is an example of how you could do it:
rust iterate over struct fields
struct Point { x: i32, y: i32, } fn main() { let point = Point { x: 3, y: 4 }; for (x, y) in &point { println!("The x coordinate is {} and the y coordinate is {}", x, y); } }
This will print:
The x coordinate is 3 and the y coordinate is 4
If you want to get the field names as well as the values, you can use a match
expression inside the loop, like this:
struct Point { x: i32, y: i32, } fn main() { let point = Point { x: 3, y: 4 }; for (name, value) in &point { match name { "x" => println!("The x coordinate is {}", value), "y" => println!("The y coordinate is {}", value), _ => (), } } }
This will also print:
The x coordinate is 3 The y coordinate is 4
Keep in mind that this technique only works if the struct has #[derive(Debug)]
or #[derive(Clone)]
attributes, since these attributes are required to get an iterator over the fields of the struct.