home.social

#rusttip — Public Fediverse posts

Live and recent posts from across the Fediverse tagged #rusttip, aggregated by home.social.

  1. Did you know that you can add doc aliases to your #Rust items (struct, method etc.), so that they appear in #RustDoc search results, when searching for that alias?🔍

    doc.rust-lang.org/rustdoc/adva

    You can even add multiple aliases at once, like this:

    #[doc(alias("modify", "index"))]
    pub fn modified_field_indices(...);

    Such a useful feature (that should be used more often)!

    ⚠️ Note that it will only show in results, when searching for the full alias!

    #RustLang #Search #RustTip #Documentation #UX

  2. If you get weird #Rust #Lifetime #error's: have you already tried to just _remove_ the lifetime annotations and see what happens? You'll often get much better error messages this way. :ferris:

    If this doesn't work and you still can't figure it out: try to not use references and own your values instead.

    #RustLang #RustTip #RustTips #FerrisTipOfTheDay

  3. Did you know that a lot of things in #Rust directly implement the `Ord` trait?

    For example `Option<T>` where T: Ord

    doc.rust-lang.org/std/option/e

    So you can do:

    assert_eq(max(Some(0), Some(1)), Some(1))

    assert_eq(max(Some(0), None), Some(0))

    assert_eq(min(Some(0), None), None)

    There are a lot of other things that implement `Ord`:
    doc.rust-lang.org/std/cmp/trai

    #RustLang #RustTips #RustTip

  4. Oh wow, did you know that in #Rust you can use Option as an iterator such that your types align, when you want to return a chain of iterators from a function, but also have an else case where the iterator is empty!?

    I know, this was a mouthful.😳

    Let's look at a playground that shows this:
    play.rust-lang.org/?version=st

    This trick is right from the docs on option:

    doc.rust-lang.org/stable/std/o

    What a cunning trick!🤓

    Rust, I ❤️ you!

    #RustTip #RustTips #RustLang