<ao> | Adetunji's Blog

Destructing struct

Destructuring let's us create variable that are not part of the structure, we can get values from a struct or enum using let backwards.

struct Person{
  name: String,
  age: u8,
  height: u8,
  happy: bool,
}

fn main(){
  let adetunji = Person{
    name: String::from("Adetunji Ojekunle"),
    age: 29,
    height: 170,
    happy: true
  };

  let Person{name,happy,..} = adetunji;

  println!("Hey, I am {name} and I am happy: {happy}");
}

The .. tells the compiler I want to ignore the other values (height and happy), if not there will be a pattern does not match error as the pattern on the right must match the one on the left.

I can also rename variables as I destructure. Say I want to rename height to cm

// previous code
let Person{height = cm,..} = adetunji;
//other code

Destructuring can also happen in a function signature.

fn introduce_person(person: &Person){
  println!("Hello!, {person.name}");
}

With Destructuring, this will be

fn introduce_person({name,..}: &Person){
  println!("Hello!, {name}")
}

#note #rust