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: lib.rs/cargo-all-features

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: stackoverflow.com/a/28664881/2

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 {
println!("closure");
return;
};
println!("surprise");
}

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:

docs.rs/futures/0.3.4/futures/

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

docs.rs/tokio/0.2.11/tokio/syn

Rust tips boosted

How to write fast Rust code, likebike.com/posts/How_To_Writ.

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

"What will Rust development look like in 2020? That's partially up to you!"

folks are calling for blog posts

"We are accepting ideas about almost anything having to do with Rust: language features, tooling needs, community programs, ecosystem needs... if it's related to Rust, we want to hear about it."

blog.rust-lang.org/2019/10/29/

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:

jethrogb.github.io/rust-combin

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:

github.com/exphp-share/unsafe-

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.

More: saghm.github.io/five-rust-thin

Multiple tips here: github.com/spacejam/elements-o

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:

crates.rs/development-tools/ca

e.g. cargo install cargo-edit

Show installed ones with cargo --list

Rust tips boosted

--------#rust----------
rust macro println!("...") is based on the rust macro format!("...").
Print version prints on the stdio whereas the format will print on a std::String.

rust println/format macros also allow convenient formatting in binary and hexadecimal.

println!("0x{:04X}", 1000); will print 0x03E8 and
println!("b'{:08b}'", 2); will print b'00000010' as an example.

-----------------------
Please reply to report error rust:1008

Shared references in don't have to be immutable. Interior mutability allows safely "cheating" the type system.

There are a few wrapper types for this, because each has a single-threaded and a multi-threaded version:

Rc → Arc
RefCell → Mutex
Cell<usize> → AtomicUsize

manishearth.github.io/blog/201

Rust tips boosted

When Rust doesn't allow you to unwrap an `Option`, use `.as_ref()`.

Unwrapping `&Option<Foo>` causes "cannot move out of borrowed content" error, because it assumes you want to take ownership of `Foo`, and that's not allowed through a reference.

`option.as_ref()` flips it inside-out to become `Option<&Foo>`, and `unwrap()` will get a reference rather than ownership, which is fine.

Try it: is.gd/3lPJqk

Show more
Octodon

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