7.0 KiB
cheat-sheet-rust
Here is the IO-Project cheat sheet to quickly learn the "Rust" programming language
Table of Contents
Basics
Rust is a systems programming language that runs blazingly fast, prevents segfaults, and guarantees thread safety. We will start now by introducing the basic concepts of the Rust language such as variables, loops, functions.
Useful cargo commands
cargo new <project_name>
: Create a new projectcargo build
: Build the projectcargo run
: Build and run the projectcargo check
: Check if the project can be builtcargo build --release
: Build the project in release modecargo update
: Update the dependenciescargo doc --open
: Generate the documentation and open it in the browsercargo test
: Run the testscargo test -- --nocapture
: Run the tests and show the output of the testscargo test -- --ignored
: Run the tests that are ignoredcargo test <test_name>
: Run the tests that match the test name
Code comments
When you start learning a new language, it's important to know how to comment the code. In ruste there are a large number of ways of commenting code. You'll also notice that the norm is 4 spaces for indentation, not tabs or 2 spaces.
//! A doc comment that applies to the implicit anonymous module of this crate
pub mod outer_module {
//! - Inner line doc
//!! - Still an inner line doc (but with a bang at the beginning)
/*! - Inner block doc */
/*!! - Still an inner block doc (but with a bang at the beginning) */
// - Only a comment
/// - Outer line doc (exactly 3 slashes)
//// - Only a comment
/* - Only a comment */
/** - Outer block doc (exactly) 2 asterisks */
/*** - Only a comment */
pub mod inner_module {}
pub mod nested_comments {
/* In Rust /* we can /* nest comments */ */ */
// All three types of block comments can contain or be nested inside
// any other type:
/* /* */ /** */ /*! */ */
/*! /* */ /** */ /*! */ */
/** /* */ /** */ /*! */ */
pub mod dummy_item {}
}
pub mod degenerate_cases {
// empty inner line doc
//!
// empty inner block doc
/*!*/
// empty line comment
//
// empty outer line doc
///
// empty block comment
/**/
pub mod dummy_item {}
// empty 2-asterisk block isn't a doc block, it is a block comment
/***/
}
/* The next one isn't allowed because outer doc comments
require an item that will receive the doc */
/// Where is my item?
}
Variables
By default in rust variable are immutable. If you want to make a variable mutable you need to add the keyword mut
before the variable name. We recommend to use immutable variables as much as possible because it's safer for two reason. First, Rust ensures that used memory is deallocated when the program is compiled, as this programming language does not have a garbage collector. Second, it is easier to reason about immutable variables because you know that the value will not change.
fn main() {
/// Immutable variable (will throw an error)
let x = 5;
println!("The value of x is: {}", x); //! --> The value of x is: 5
x = 6; // This will throw an error because x is immutable
//// Mutable variable
let mut x = 5;
println!("The value of x is: {}", x); //! --> The value of x is: 5
x = 6; // This will not throw an error because x is mutable
println!("The value of x is: {}", x); //! --> The value of x is: 6
//// Shadowing variable
let x = 5;
println!("The value of x is: {}", x); //! --> The value of x is: 5
let x = x + 1; // This will not throw an error because we are creating a new variable and shadowing the previous one
println!("The value of x is: {}", x); //! --> The value of x is: 6
}
You can also declare a constant variable using the const
keyword. The type of the variable must be specified and it will be immutable. Constants can be declared anywhere, the variable name must be in uppercase and the value must be a constant expression, not the result of a function call or any other value that could only be calculated at runtime.
fn main() {
//// Constants
const HEAL_POINTS: u32 = 100_000 * 5;
println!("The value of HEAL_POINTS is: {}", HEAL_POINTS); //! --> The value of HEAL_POINTS is: 500000
}
Data types
Rust is a statically typed language, which means that it must know the types of all variables at compile time. The compiler can usually infer what type we want to use based on the value and how we use it. In addition, we can add type annotation to indicate which type we want to use.
fn main() {
// Convert a string to integer by specifying the type
let guess: u32 = "42".parse().expect("Not a number!"); // The type mus be specified (u32)
println!("The value of guess is: {}", guess); //! --> The value of guess is: 42
}
Scalar types
A scalar type represents a single value. Rust has four primary scalar types: integers, floating-point numbers, Booleans, and characters.
Length | Signed | Unsigned |
---|---|---|
8-bit | i8 | u8 |
16-bit | i16 | u16 |
32-bit | i32 | u32 |
64-bit | i64 | u64 |
128-bit | i128 | u128 |
arch | isize | usize |
Number literals | Example |
---|---|
Decimal | 98_222 |
Hex | 0xff |
Octal | 0o77 |
Binary | 0b1111_0000 |
Byte (u8 only) | b'A' |
In Rust you can cast one type into another using the as
keyword. You can also specify the signature of a number using the suffix _type
(e.g. 5_i32
).
fn main() {
//// Integer types
let x: u32 = 5 as u32; // Unsigned integer
let x: i32 = 5; // Signed integer (default one)
//// Floating-point types
let x: f32 = 5.0_f32; // 32-bit floating-point number
let x: f64 = 5.0; // 64-bit floating-point number (default one)
//// Boolean types
let x: bool = true; // Boolean type
//// Character types
let x: char = 'x'; // Character type
/// Numeric operations
let sum = 5 + 10; // Addition
let difference = 95.5 - 4.3; // Subtraction
let product = 4 * 30; // Multiplication
let quotient = 56.7 / 32.2; // Division
let remainder = 43 % 5; // Remainder
/// If statements
let number: i32 = 3;
if number < 5 {
println!("number smaller than 5"); //! --> condition was true
} else if number > 25 {
println!("number bigger than 25");
} else {
println!("number between 5 and 25");
}
Functions
fn main() {
}