Some underrated features of Rust
This will be an opinionated post about some of the useful features of the Rust Programming language. They are underrated and often don't even get mentioned as useful programming language features.
Imports scoped to a code block / Local Imports
You are used to having all the imports at the beginning of the file - even those used just once in a function.
use some::{Person, Address};
use other::Thing;
fn save(a: Address) {
Person:new().with_address(a);
}
fn process() {
// [...]
Thing::do();
// [...]
Thing::do_another_thing();
}
The process
function can import the other::Thing
in place or scope within the function. This makes it easier to cut-paste the entire function to another module if needed, and all the imports will follow you.
// [...]
fn process() {
use other::Thing;
// [...]
Thing::do();
// [...]
Thing::do_another_thing();
}
I prefer this when I import a type that is only used once. It can make your code much more readable and reduce noise at the beginning of the code file.
fn another_example(o: Order) {
match o {
package::model::OrderType::Pending(p) => todo!(),
package::model::OrderType::Shipped(p) => todo!(),
package::model::OrderType::Delivered(p) => todo!(),
}
}
fn another_example_better(o: Order) {
use package::model::OrderType;
match o {
OrderType::Pending(p) => todo!(),
OrderType::Shipped(p) => todo!(),
OrderType::Delivered(p) => todo!(),
}
}
Use if/match/loop expression to return value
This is usually the first thing I miss about Rust when I switch popular backend languages.
In Rust, if
, match
, loop
etc. all are expressions. That means they all can return value. This makes initialization with the default or setting the value of a variable concise.
let delivery_speed = match order.user.membership_type {
Member::Platinum => Delivery::Today,
Member::Gold => Delivery::NextDay,
Member::Free => Delivery::Slow,
};
Compare this to
function getDeliverySpeed(order: Order): Delivery {
switch (order.user.membership_type) {
case Membership.Platinum:
return Delivery.Today;
case Membership.Gold:
return Delivery.NextDay;
case Membership.Free:
return Delivery.Slow;
default:
throw new Error("Invalid membership type");
}
}
const delivery_speed = getDeliverySpeed(order);
Let me know if you have any favourite underrated Rust Language feature in the comment.