Basics
std
is the standard rust
library.
- Libraries brought into the scope by
rust
from the std
library are called the prelude.
- Statements are instructions that perform some action and do not return a value.
- Expressions evaluate to a resultant value. They don't end with a semicolon.
Syntax
- They are always the same:
// Rust use only the one line comment
// so you don't have to worry about various
// styles!
Main
- This is how you start a rust program:
fn main() {
// Program
}
Imports
- Bring some library into the scope:
use std::io;
Constants and variables
let x = 5;
let x = 6;
// Forbidden: x = 6
let mut x = 5;
x = 6;
const I_AM_A_CONSTANT: u32 = 42;
Tuples
let tuple: (i32, f32, bool, char) = (500, 6.4, true, 'a');
let (i,f,b,c) = tuple; // Deconstruction
let f = tuple.1; // Field access
Arrays
let x = [1,2,3,4,4];
let x: [i32; 5] = [1,2,3,4,4];
let x = [4; 5]; // = [4, 4, 4, 4, 4];
let first = x[0];
Functions
fn function_name(arg: i32) -> i32 {
return arg + 2;
}
Printing
- We can print value using
println!
placeholders:
let x = 1;
let y = 2;
println!("x = {x}, y = {}", y);
Pattern matching
let x = match res {
Ok(num) => num,
Err(_) => continue,
}
If-then-else
if-then-else
acts like a variable and can be consume by a variable or as a return expression from a function.
if boolean_expression {
// Case one!
} else if another_expression {
// Another case!
} else {
// Final case!
}
Loop
loop {
// Need a break; to leave this loop.
}
- Infinite loop with return result:
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
'label: loop {
break 'label;
}
let mut number = 10;
while number != 0 {
number -= 1;
}
for element in collection {
// Do something.
}
for number in (0..4) {
// Do something too.
}
Cmdline
Rustc
- To compile a code, just run:
rustc file.rs
./file
Cargo
Create a new project
cargo new <project_name>
Build a project
cargo build
Build and run a project
cargo run
Check the code is correct
cargo check
Resources
Library docs
Learning