Pinned oot
Rust tips boosted

I've had a but of trouble with modules in #rust. It's different in style than what I'm used to in #python it #r.

This blog post has a good, clear explanation of what you need to do and what's going on, with some good simple examples

Rust tips boosted

cargo install cargo-edit

and you'll be able to add dependencies with just

cargo add <crate-name>

Rust tips boosted

If you have an iterator of `Result`s, you can collect and unwrap all values into a `Vec` on success or return the first `Err` found:

let files_contents = file_names.iter().map(read_file).collect::<Result<Vec<_>, _>>()?;

If you did `.collect::<Vec<_>>()` instead, you'd have an array of mixed `Ok`/`Err` values.

See in playground:

If you want to create an async stream, the easy solution is a generator macro:

It lets you write the stream as a loop with `yield` instead of implementing traits and managing state manually.

Rust tips boosted

When you create a function expecting an optional reference, use `Option<&Foo>` rather than `&Option<Foo>`.

fn optional(good: Option<&Foo>, bad: &Option<Foo>) {…}

Both optimize to the same representation, but `Option<&Foo>` is easier to work with, and is more universal, because it can be cheaply created from an owned option with `.as_ref()`.

Does your crate have optional features? Are you sure all combinations of the feature flags work correctly? You can verify this with this cargo plugin:

In you can cast concrete type to an abstract trait object (e.g. `&i32` as `&dyn Debug`), but you can't (yet) cast a trait object as another trait (e.g. `dyn Error` can't be cast as `dyn Debug`).

The workaround is to add a method to the trait that asks for a different dyn type (e.g. `as_debug(&self) -> &dyn Debug`). That allows trait implementers to cast their concrete type.

This workaround can be automated:

async {} block in behaves like a closure. It does _not_ run any code automatically. It only creates an inactive object, which has to be spawned or awaited to start doing anything.

Example of incorrect usage:

fn main() {
async {

It prints "surprise", and nothing else!

Dropping of a stops its execution. There's also a higher-level wrapper that makes Futures cancellable on demand:

You can limit number of asynchronous tasks running at once (e.g. number of requests to a back-end) with a Semaphore

Rust tips boosted

How to write fast Rust code,

A collection of tips and tricks to improve Rust code performance.

#rustlang #performance

Rust tips boosted

TIL you can have multiple impl's for the same struct in different files, to put logical groups of functions into separate files.

#rustlang #rust

Rust tips boosted

Since people may not have heard of it, here's a non threaded PSA post: add `--document-private-items` to `cargo doc` to get a nice reference for your own #rust code.

The latest version of started warning about missing `dyn` keywords. You don't have to add them by hand! Run:

cargo fix --edition-idioms

and it'll automatically add all the missing bits of the syntax.

How to convert an Option/Result/Iterator into another kind of Option/Result/Iterator? Here's a tool that lists all the options:

Unsafe code in still has to uphold language's safety properties. Some things are really hard to get right. Here's a mini guide of unsafe gotchas:

You can print numbers and strings padded to a fixed number of characters, e.g.:

println!("{:>5}", num);

Prints a number, right-aligned, padded to 5 characters. {:<5} left-aligns, {:^5} centers.


Multiple tips here:

e.g. instead of nesting match statements:

match a {
Some(a) => {
match b {

you can match multiple values at the same time:

match (a, b) {
(Some(a), Some(b)) => …

You can extend Cargo's functionality by installing new subcommands:

e.g. cargo install cargo-edit

Show installed ones with cargo --list

Show more

The social network of the future: No ads, no corporate surveillance, ethical design, and decentralization! Own your data with Mastodon!