Yet another SWE Blog.
Why object destructuring is awesome
Nigel Schuster
Object destructuring is a syntax that allows you to unpack values from an object. Many modern languages have support for it. So let's have a look at an example:
struct User {
name: String,
age: u8
}
// Bad: This how I would naively write this
impl ToString for User {
fn to_string(&self) -> String {
format!("{name} ({age})", name=self.name, age=self.age)
}
}
// Good: Take advantage of destructuring
impl ToString for User {
fn to_string(&self) -> String {
let User { name, age } = self;
format!("{name} ({age})", name=name, age=age)
}
}
Why does it matter? Well, let's have a look what happens when we add a field:
struct User {
name: String,
age: u8,
height: u16 // in cm
}
The bad example will compile perfectly fine. Meanwhile when using destructuring we get:
error[E0027]: pattern does not mention field `height`
--> src/lib.rs:9:13
|
9 | let User { name, age } = self;
| ^^^^^^^^^^^^^^^^^^ missing field `height`
|
help: include the missing field in the pattern
|
9 | let User { name, age, height } = self;
| ^^^^^^^^^^
help: if you don't care about this missing field, you can explicitly ignore it
|
9 | let User { name, age, .. } = self;
| ^^^^^^
Thanks to object destructuring we remember to update our code:
impl ToString for User {
fn to_string(&self) -> String {
let User { name, age, height } = self;
format!("{name} ({age}, {height} cm)", name=name, age=age, height=height)
}
}
Published on 2021-08-28.