Module 4 • Lesson 23

Destructuring Patterns

📚 8 min read💻 Free Course🦀 nixus.pro

Destructuring Everywhere

fn main() {
    // Tuple destructuring
    let (a, b, c) = (1, "hello", 3.14);
    println!("{} {} {}", a, b, c);

    let (first, ..) = (1, 2, 3, 4, 5);  // ignore rest with ..
    let (x, _, z) = (10, 20, 30);        // ignore middle with _

    // Struct destructuring
    struct Point { x: i32, y: i32 }
    let p = Point { x: 3, y: -7 };
    let Point { x, y } = p;
    println!("x={} y={}", x, y);

    // With renaming
    let p2 = Point { x: 1, y: 2 };
    let Point { x: px, y: py } = p2;

    // Nested
    let ((r, g), b) = ((255, 128), 0u8);
    println!("rgb({},{},{})", r, g, b);

    // In function parameters
    fn distance(&(x1, y1): &(f64, f64), &(x2, y2): &(f64, f64)) -> f64 {
        ((x2-x1).powi(2) + (y2-y1).powi(2)).sqrt()
    }
    let a = (0.0, 0.0);
    let b = (3.0, 4.0);
    println!("distance: {}", distance(&a, &b)); // 5.0

    // In for loops
    let pairs = vec![(1,"one"), (2,"two"), (3,"three")];
    for (n, name) in &pairs {
        println!("{} = {}", n, name);
    }
}

🎯 Practice

  1. Destructure a Vec<(String, u32, bool)> in a for loop to print each field separately
  2. Write a function taking (&Point3D, &Point3D) where Point3D = struct { x,y,z: f64 } and returning distance
  3. Destructure nested ((a, b), (c, d)) = ((1,2),(3,4)) and use all four values

🎉 Key Takeaways