Pinned oot
Rust tips boosted

The yearly state of #Rust survey is out.🎉 You can take part until the 24th of September.
Please help the Rust community improve the Rust ecosystem by taking part in the survey. It should take less than 15 minutes:


constants create a new temporary value every time you mention them.

You can do with whatever you want with the temporary value from a constant, even mutate it. But it only affects each temporary copy, not the constant.

use std::cell::Cell;

const C: Cell<bool> = Cell::new(false);

fn main() {
assert_eq!(false, C.get());

If your project depends on a Nightly version of the compiler, you can create `rust-toolchain` file with the required version. It will make Cargo automatically switch to the right compiler for the build.

If you're defining an alias for your crate's Result type, instead of:

type Result<T> = std::result::Result<T, MyError>;


type Result<T, E = MyError> = std::result::Result<T, E>;

This still works as `Result<()>`, but doesn't cause errors when someone accidentally shadows std's Result with it. It also makes Rustdoc display the error type explicitly in the documentation.

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:

Show more

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