#rusttip — Public Fediverse posts
Live and recent posts from across the Fediverse tagged #rusttip, aggregated by home.social.
-
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?🔍
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!
-
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.
-
Did you know that a lot of things in #Rust directly implement the `Ord` trait?
For example `Option<T>` where T: Ord
https://doc.rust-lang.org/std/option/enum.Option.html#impl-Ord-for-Option%3CT%3E
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`:
https://doc.rust-lang.org/std/cmp/trait.Ord.html#implementors -
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:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=129eb419d767b71447b408e456773555This trick is right from the docs on option:
https://doc.rust-lang.org/stable/std/option/#iterating-over-option
What a cunning trick!🤓
Rust, I ❤️ you!