Skip to content

Some neat things about Rust

Tyler Gamvrelis edited this page May 26, 2022 · 10 revisions
  • Won't compile code that reads uninitialized variables
  • Variables and struct properties are immutable (read-only) by default
  • Rust doesn't have exceptions. Uses lots of enums along with match statements, which ensure that every possible case is handled in code (e.g., error cases are not ignored, although they can be passed to the caller)
  • A variable can either have one mutable reference to it and no immutable references to it, or can have an arbitrary number of immutable references to it
  • Reference system ensures that the scenario of a null pointer being dereferenced will never arise
  • Rust does not actually have null, but it does provide the Option enum which encodes the concept of a value either being present (Some) or absent (None)
  • Borrow checker compares the lifetime of a reference to the lifetime of the underlying value it refers to, to ensure references are always valid
  • Won't compile any code with the possibility of a dangling reference (e.g., function that returns a reference to local data)
  • Function return values that are references (or contain references) must be connected to (at least) one of the function's arguments using lifetimes. This makes sense, because a reference that is returned cannot be referring to data local to the function, thus it must be referring to some external data that was passed into it. Except for some special cases (lifetime elision rules), the Rust compiler cannot deduce the lifetimes with certainty, so they must be explicitly annotated
  • Traits allow you to add type constraints to generics
  • Documentation comments are triple-slashed, ///, and support Markdown for formatting. There's also documentation for contained items, which is started using //!. Running cargo doc will build the documentation
  • Some typical documentation sections are: Examples, Panics, Errors and Safety
  • Code snippets in documentation comments are initiated with triple ticks, and can be compiled and checked for correctness using cargo test
  • Unit tests go in the same file as the code they test, while integration tests go in a /tests folder next to /src. There are lots of command-line options when running cargo test, such as specifying a particular test by name or a particular set of tests by a substring their names have in common
  • Publishing a crate to crates.io is an irreversible action: that code will be made available indefinitely
  • Multiple related crates that are developed in tandem can be managed using Cargo workspaces. A workspace is a set of packages sharing the same Cargo.lock and output directory
  • Cargo can be extended using custom commands, without having to modify Cargo. For example, you can use cargo install to install extensions and run them like built-in commands

Clone this wiki locally