Some neat things about Rust you might not know

421 points bitfieldconsulting 107 comments

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 with iter::from_fn.

  • You can collect() an iterator of Results into a Result<Vec>, so you'll either get all the Ok results, or the first Err.

  • You can gate a derive(Bar) behind a feature flag foo, with cfg_attr(feature = "foo", derive(Bar)].

  • If you have a struct with pub fields but you don't want users to be able to construct an instance of it, mark it non_exhaustive.

  • To match a String against static strs, use as_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?