Shavings - Small Bits of Rust Knowledge

Shavings - Small Bits of Rust Knowledge

Last Updated: October 14th, 2018
There's a lot of neat things about Rust that are not long enough for a blog post but would be neat to have written down somewhere. I've written this post to be a collection of those small bits of Rust knowledge that satisfy just that


Into::into

Sometimes you might be writing some iterator code or you might have an Option or Result type that needs to get converted to another type. You might write some code like this:

let bar = foo.map(|i| i.into());

However, you can shorten that with:

let bar = foo.map(Into::into);

It's just slightly more readable by removing some closure symbols and a bit more terse by declaring, "This map does one thing and one thing only: converting the type".


Pretty Debug Print

It's common to print out debug info with:

println!("{:?}", my_debug_struct);

But it tends to not be what people want to lay things out when printing something like a deserialized JSON blob. You can do so with this instead:

println!("{:#?}", my_debug_struct);

OS Specific Crates

You might know that you can make some code only compile on specific OS with:

#[cfg(windows)]

However, in your Cargo.toml file you can also specify crates only get linked in on specific OS with a cfg used to specify which platform the dependency should show up in:

[target.'cfg(windows)'.dependencies]
winapi = { version = "0.3", features = ["winuser"] }

This can also be used to make it get linked in only on specific things such as when cargo test is run using cfg(test) perfect for crates such as proptest.