Some neat things about Rust you might not know
Hi r/rust, I'm John Arundel. You may remember me from such books as The Secrets of Rust: Tools, but I'm not here about that. I'm collecting material for a new book all about useful Rust tips, tricks, techniques, crates, and features that not everyone knows.
Every time I learned something neat about Rust, I wrote it down so I'd remember it. Eventually, the list got so long it could fill a book, and here we are! I'll give you a few examples of the kind of thing I mean:
Got a function or closure that returns
Option<T>? Turn it into an iterator withiter::from_fn.You can
collect()an iterator ofResultsinto aResult<Vec>, so you'll either get all theOkresults, or the firstErr.You can gate a
derive(Bar)behind a feature flagfoo, withcfg_attr(feature = "foo", derive(Bar)].If you have a struct with
pubfields but you don't want users to be able to construct an instance of it, mark itnon_exhaustive.To match a
Stringagainst staticstrs, useas_str():match stringthing.as_str() { “a” => println!(“0”), “b” => println!(“1”), “c” => println!(“2”), _ => println!(“something else!”), }
The idea is that no matter how much or how little Rust experience you have, there'll be something useful in the book for you. I've got a huge file of these already, but Rust is infinite, and so is my ignorance. Over to you—what are your favourite neat things in Rust that someone might not know?