Pinned post

If you're looking for good crates, use lib.rs to search. It has much better ranking algorithm than crates.io.

Compare:

crates.io/search?q=option
vs
lib.rs/search?q=option

Rustdoc documentation supports embedding external files using include_str!(), like other expressions.

If you want to reuse your README file for your library's documentation on docs.rs, put this at the top of the src/lib.rs:

#![doc = include_str!("README.md")]

To find unused dependencies, compile your program with:

cargo rustc -- -W unused_crate_dependencies

In you can return std::process::ExitCode from main().

It's better than calling std::process::exit(), because it allows the program to run destructors, which may be needed to flush pending I/O or print buffered logs.

play.rust-lang.org/?gist=56c6f

doc.rust-lang.org/stable/std/p

The latest nightly version has an option to build or install crates without downloading the full crates-io index. This can be a big speed boost for Dockerized builds and Continious Integration that doesn't cache .cargo directory.

Try it out:

internals.rust-lang.org/t/call

You can easily pass ownership of objects to C. There's no need to use `Box::into_raw()` or any unsafe trickery. Box is FFI-safe, and can be used as a return type directly:

stackoverflow.com/a/46677043/2

Did you know crates.io has added new categories? Make your crate easier to find. Add categories to your Cargo.toml:

categories = ["insert category slugs here"]

crates.io/category_slugs

Rust tips boosted

#TIL that you can disallow certain types in your #Rust code with #Clippy (since 1.55):

nnethercote.github.io/perf-boo

This is useful, if you e.g. want to use a faster HashMap (e.g. from ahash) and not the std HashMap.

Official docs:
rust-lang.github.io/rust-clipp

#Lint #RustLang

Compare the uncomparable! enum variants can be compared with `==` only if they implement the `PartialEq` trait, but that isn't always available or convenient for enums with complex data.
However, the `match` expression always works, and there's a handy `matches!()` macro for one-off comparisons.

if value == SomeEnum::Variant(data) { /* maybe */ }
if matches!(value, SomeEnum::Variant(_)) { /* ok */ }

More examples:
play.rust-lang.org/?gist=35907

If you're developing or applications, you can add dependencies to your projects using lib.rs/cargo-xcode

cargo clippy --fix

will automatically apply code improvement suggestions from Clippy. Not every issue can be automatically corrected, so it's still worth running `cargo clippy` afterwards.

Common Rust Lifetime Misconceptions — very helpful resource that helps avoid fighting the borrow checker:

github.com/pretzelhammer/rust-

Rust tips boosted

Use the following to include your README in your `doctest`s (so that your examples in your README are also executed).

#[doc = include_str!("../README.md")]
#[cfg(doctest)]
pub struct ReadmeDoctests;

See here:
doc.rust-lang.org/rustdoc/docu

#Rust #RustLang #RustDoc #Documentation #Docs #RustTip

You can convert a slice (or a `Vec`) to a fixed-length array using the `TryInto` trait:

let arr: [_; 4] = slice[..4].try_into().unwrap();

It's a bit verbose, but the `.try_into().unwrap()` part will be optimized out entirely whenever the compiler can see the slice is long enough.

rust.godbolt.org/z/GGTnr1Pqz

"Unfortunately" this doesn't generalize to all attributes, so you can't have a cursed syntax like that:

struct Lol {
#![derive(Copy, Clone, Debug)]
}

fn nope() {
#![test]
}

Show thread

has meta attributes that can apply to entire modules, like #[cfg(…)], #[allow(…)] and #[deny(…)].

The #[…] attribute syntax used outside of a module is equivalent to #![…] syntax inside it:

#[cfg(windows)]
mod win {
}

mod win {
#![cfg(windows)]
}

You have to use #![…] attribute syntax at the top of the lib.rs file, because there's no outer file that has the `mod` declaration for lib.rs.

The `.get()` method on a `Vec` or `HashMap` will only temporarily borrow an item, and you won't be allowed to move it or use it outside of the scope of the `.get()` call.

If you want to get an _owned_, freely movable value, use `.remove()` instead.

If you need to have an owned value without removing elements from the collection, you're going to have to clone. Clone can be fast if items are wrapped in `Rc` or `Arc`.

play.rust-lang.org/?gist=a7ccf

Do you want io::Read::read_exact(), but read into a Vec instead?

let bytes_read = reader
.by_ref() // optional: avoids consuming the reader
.take(length_to_read) // limits number of bytes
.read_to_end(&mut vec)?; // reads up to the limit
// the file could have ended sooner, so needs a check
if bytes_read != length_to_read { return Err("EOF") }

play.rust-lang.org/?gist=05ac9

A few design patterns/idioms that you need to change if you're switching from to :

cppfaq.rs

Show older
Octodon

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