Rust Cheat Sheet

In Rust

Rust is a modern programming language that has been gaining popularity in recent years. It was created by Mozilla and is designed to be fast, safe, and concurrent. Rust is a systems programming language, which means it is used to build low-level software such as operating systems, device drivers, and embedded systems.

One of the key features of Rust is its memory safety. Rust uses a unique ownership model that ensures memory safety at compile time. This means that Rust programs are less likely to have memory-related bugs such as null pointer dereferences, buffer overflows, and use-after-free errors. Rust also has a powerful type system that helps catch errors at compile time.

Another important feature of Rust is its performance. Rust is designed to be fast and efficient, making it a great choice for building high-performance software. Rust’s performance is achieved through its low-level control over memory and its ability to compile to native code.

Rust is also a highly concurrent language. It has built-in support for concurrency and parallelism, making it easy to write programs that take advantage of multiple cores and threads. Rust’s concurrency features are designed to be safe and easy to use, making it a great choice for building scalable and high-performance software.

Table of Contents

Variables

SyntaxDescription
let x = 5;Declares a variable x and assigns it the value 5.
let mut x = 5;Declares a mutable variable x and assigns it the value 5.
let x: i32 = 5;Declares a variable x of type i32 and assigns it the value 5.
let x = ""hello"";Declares a variable x of type &str and assigns it the value ""hello"".
const PI: f32 = 3.14;Declares a constant PI of type f32 and assigns it the value 3.14.

Data Types

TypeDescription
i8, i16, i32, i64, i128Signed integers of various sizes.
u8, u16, u32, u64, u128Unsigned integers of various sizes.
f32, f64Floating-point numbers of various sizes.
boolBoolean values (true or false).
charA single Unicode character.
&strA string slice (a reference to a string).
StringA heap-allocated string.
()The unit type (has only one value, ()).
Option<T>An optional value that may or may not be present.
Result<T, E>A value that represents either success (Ok(T)) or failure (Err(E)).
ArrayA fixed-size array of elements of the same type.
Vec<T>A dynamically-sized vector (a heap-allocated array).
TupleA fixed-size collection of values of different types.
StructA custom data type that groups together values of different types.
EnumA custom data type that represents a value that can be one of several variants.

Control Flow

SyntaxDescription
if condition { ... } else { ... }Executes the code in the first block if the condition is true, otherwise executes the code in the second block.
while condition { ... }Repeatedly executes the code in the block as long as the condition is true.
for item in iterable { ... }Iterates over the elements of an iterable and executes the code in the block for each element.
match value { pattern => { ... }, ... }Matches a value against a set of patterns and executes the code in the block for the first matching pattern.
loop { ... }Repeatedly executes the code in the block indefinitely.
breakExits the innermost loop or block.
continueSkips the rest of the current iteration of the innermost loop.

Functions

SyntaxDescription
fn name(param1: Type1, param2: Type2) -> ReturnType { ... }Declares a function with the given name, parameters, and return type.
fn name() -> impl Trait { ... }Declares a function that returns a type that implements the given trait.
fn name<T: Trait>(param: T) -> ReturnType { ... }Declares a function that takes a parameter of a type that implements the given trait.
fn name(param: Type) -> Result<ReturnType, ErrorType> { ... }Declares a function that returns a Result type indicating success or failure.
fn name(param: Type) -> Option<ReturnType> { ... }Declares a function that returns an Option type indicating whether a value is present or not.

Ownership

SyntaxDescription
let x = String::from(""hello"");Allocates a new String on the heap and assigns it to x.
let y = x;Moves the ownership of x to y, making x invalid.
let y = x.clone();Creates a new String on the heap and assigns it to y, copying the contents of x.
fn do_something(s: String) { ... }Takes ownership of a String and performs some operation on it.
fn do_something(s: &String) { ... }Borrows a reference to a String and performs some operation on it.
fn do_something(s: &mut String) { ... }Borrows a mutable reference to a String and performs some operation on it.

Borrowing

SyntaxDescription
let s = String::from(""hello"");Allocates a new String on the heap and assigns it to s.
let len = calculate_length(&s);Borrows a reference to s and passes it to a function that calculates its length.
fn calculate_length(s: &String) -> usize { ... }Borrows a reference to a String and returns its length.
let mut s = String::from(""hello"");Allocates a new String on the heap and assigns it to s.
change(&mut s);Borrows a mutable reference to s and modifies its contents.
fn change(s: &mut String) { ... }Borrows a mutable reference to a String and modifies its contents.

Structs

SyntaxDescription
struct Point { x: i32, y: i32 }Declares a struct Point with two fields x and y of type i32.
let p = Point { x: 0, y: 0 };Creates a new instance of Point with the given field values.
let x = p.x;Accesses the field x of the struct p.
impl Point { fn distance_from_origin(&self) -> f64 { ... } }Defines a method distance_from_origin on the Point struct that borrows a reference to self.
impl Point { fn new(x: i32, y: i32) -> Point { ... } }Defines a constructor new on the Point struct that returns a new instance of Point.

Enums

SyntaxDescription
enum Color { Red, Green, Blue }Declares an enum Color with three variants Red, Green, and Blue.
let c = Color::Red;Creates a new instance of Color with the variant Red.
match c { Color::Red => { ... }, ... }Matches the variant of c and executes the code in the block for the first matching variant.
enum Option<T> { None, Some(T) }Declares an enum Option with two variants None and Some that can contain a value of type T.
enum Result<T, E> { Ok(T), Err(E) }Declares an enum Result with two variants Ok and Err that can contain a value of type T or E.

Traits

SyntaxDescription
trait MyTrait { fn my_method(&self) -> usize; }Declares a trait MyTrait with a method my_method that borrows a reference to self.
struct MyStruct { ... }
impl MyTrait for MyStruct { ... }
Implements the trait MyTrait for the struct MyStruct.
fn my_function<T: MyTrait>(x: T) -> usize { ... }Takes a parameter x of a type that implements the trait MyTrait and calls its method my_method.
fn my_function<T>(x: T) -> usize where T: MyTrait { ... }Same as above, but using a where clause instead of a type constraint.

Generics

SyntaxDescription
fn my_function<T>(x: T) -> T { ... }Declares a function my_function that takes a parameter x of any type T and returns it.
struct MyStruct<T> { ... }Declares a struct MyStruct with a generic type parameter T.
impl<T> MyStruct<T> { ... }Implements methods for the struct MyStruct that use the generic type parameter T.
fn my_function<T: MyTrait>(x: T) -> usize { ... }Declares a function my_function that takes a parameter x of a type that implements the trait MyTrait.

Modules

SyntaxDescription
mod my_module { ... }Declares a module my_module with its own scope.
use my_module::my_function;Imports the function my_function from the module my_module.
pub mod my_module { ... }Declares a public module my_module that can be accessed from other modules.
mod my_module { pub fn my_function() { ... } }Declares a function my_function that is public within the module my_module.

Crates

SyntaxDescription
extern crate my_crate;Imports the external crate my_crate.
pub mod my_module;Declares a public module my_module that can be accessed from other crates.
pub use my_module::my_function;Exports the function my_function from the module my_module to other crates.

Macros

SyntaxDescription
macro_rules! my_macro { ... }Declares a macro my_macro with its own syntax.
my_macro!(...)Invokes the macro my_macro with the given arguments.
#[derive(Debug)]Derives the Debug trait for a struct or enum.
#[test]Marks a function as a test function that can be run with cargo test.

Error Handling

SyntaxDescription
fn my_function() -> Result<(), ErrorType> { ... }Declares a function my_function that returns a Result type indicating success or failure.
let result = my_function()?;Calls my_function and returns the result if it is Ok, otherwise returns the error.
fn main() -> Result<(), Box<dyn Error>> { ... }Declares the main function that returns a Result type indicating success or failure, with the error type boxed and dynamic.
fn main() -> Result<(), MyError> { ... }
#[derive(Debug)]
struct MyError { ... }
Declares the main function that returns a Result type indicating success or failure, with a custom error type MyError.

Concurrency

SyntaxDescription
std::thread::spawn(|| { ... });Spawns a new thread and executes the code in the closure.
let handle = thread::spawn(|| { ... });
handle.join().unwrap();
Spawns a new thread and waits for it to finish, returning a JoinHandle that can be used to wait for the thread to finish.
let (tx, rx) = mpsc::channel();
tx.send(value).unwrap();
let received = rx.recv().unwrap();
Creates a new channel for sending and receiving messages between threads, and sends and receives messages on the channel.
let pool = ThreadPool::new(num_threads);
pool.execute(|| { ... });
Creates a thread pool with the given number of threads, and executes the code in the closure on one of the threads in the pool.

Reference:

https://doc.rust-lang.org/beta/

#