Packages are called crates.
To create a new project: cargo new <project_name>
. This creates a folder with a src/main.rs
file (for executable crates).
Declare variables with let
. Example:
let x = 5; // Immutable
let mut y = 10; // Mutable
Be careful with referencing mutable and immutable variables:
&var
) means you can't change the value.&mut var
) allows modification but is limited to one borrower at a time.Rust is statically typed but uses type inference to deduce types:
let x = 42; // Inferred as `i32`
let y = 3.14; // Inferred as `f64`
Expressions evaluate to a value. Example:
let x = { 5 + 3 }; // `5 + 3` is an expression
Statements perform actions but do not return a value. Example:
let x = 5; // This is a statement
Functions implicitly return the last expression if no semicolon is used:
fn add(a: i32, b: i32) -> i32 {
a + b // This is the return value
}
Ownership ensures memory safety without a garbage collector:
Borrowing refers to taking a reference to an object:
Immutable borrow:
let s = String::from("hello");
let r1 = &s; // Immutable borrow
Mutable borrow (only one allowed at a time):
let mut s = String::from("hello");
let r2 = &mut s; // Mutable borrow+
<aside> 💡
Traits provide a way to define shared behavior across different types.
Similar to Java's interfaces; they define shared behavior: