Share Rust secrets that facilitate development

Recently, yesterday, I discovered that you can use pub use mod_name to re-export a module hiding part of the original path. This is very useful for re-exporting specific modules under the same name, for example you can create a module unix :: file and another one windows :: file and re-export as file without having to create an abstraction to access specific platform versions:

# [cfg (target_family = "unix")]
pub use unix :: file;

# [cfg (target_family = "windows")]
pub use windows :: file;

If you know other useful secrets like that, tell me.

3 Likes

If I did, it would not be a secret anymore!

For actual tips:

  • reduce complexity.
  • avoid generics if not actually needed
  • don't "leak" lifetimes in the API, unless absolutely necessary.
1 Like

I collect small tips here: https://octodon.social/@rust

8 Likes

I've got some points for pratical Software Dev in Rust.

2 Likes

Maybe you'd like to revisit the Book, because there's a section about this.

Remember .clone is your friend.

With a little sprinkling of .clone one will need never have to use lifetime specifiers in ones application code.

Well, works for me so far.

1 Like

This is a good thing to remember:

That's from the cargo flamegraph README, written by a guy who I'm pretty sure is like a Rust performance expert and who writes a ridiculously fast Rust database:

2 Likes

I remember boxed array initialization to not be compiled away. I actually don't know, if Box::new ever manages to initialize something directly on the heap, TBH. Does someone know?

I agree with the other points, tho. I'd also add, that sometimes, you just have to sprinkle a bit of #[inline] to help the optimizer compile away some otherwise expensive operations, if it fails to inline, before resorting to refactoring algorithms.

1 Like

Use anyhow and it's companion thiserror for error handling.

Also worth knowing about the anyhow fork eyre which has a cool library for fancy printing your errors: color_eyre. Anyhow or Eyre are both great, but if you want fancy printing, Eyre is probably better for that.