Comments:
- Single line:
//
- Multiple lines:
/* */
Variable
- Use
letto declare a variable
- Plus
mutto declare a mutable variable
fn main() { let name = "John"; let mut age = 38; // name = "Tom"; ❌ cannot assign twice to immutable variable age = 39; println!("The age is {}, and the name is {}", age, name); }
{ }acts as a placeholder.
Data type
Basic data types in Rust are divided into different groups:
- Numbers - Whole numbers and decimal numbers (
i32,u32,f64) i32can store positive and negative whole numbersu32can only store zero or positive whole numbersf64can store numbers containing one or more decimals:
- Characters - Single letters or symbols (
char)
- Strings - Text, a sequence of characters (
&str)
- Booleans - True or false values (
bool)
Implicit:
let my_num = 5; // integer let my_double = 5.99; // float let my_letter = 'D'; // character let my_bool = true; // boolean let my_text = "Hello"; // string
Explicit:
let my_num: i32 = 5; // integer let my_double: f64 = 5.99; // float let my_letter: char = 'D'; // character let my_bool: bool = true; // boolean let my_text: &str = "Hello"; // string
Use
const to create a constant.// const BIRTHYEAR = 1990; // ❌ miss type const BIRTHYEAR: u32 = 1990;
Constants must have a data type.
If/else
Syntax:
if score >= 90 { println!("Grade: A"); } else if score >= 80 { println!("Grade: B"); } else if score >= 70 { println!("Grade: C"); } else { println!("Grade: F"); }
Use the return of if/else:
let greeting = if time < 18 { "Good day." } else { "Good evening." };
Match
fn main() { let day = 4; match day { 1 => println!("Monday"), 2 => println!("Tuesday"), 3 => println!("Wednesday"), 4 => println!("Thursday"), 5 => println!("Friday"), 6 => println!("Saturday"), 7 => println!("Sunday"), _ => println!("Invalid day."), } }
_ is the same as the default in other languages.Multiple match, use the
| operator (OR):match day { 1 | 2 | 3 | 4 | 5 => println!("Weekday"), 6 | 7 => println!("Weekend"), _ => println!("Invalid day"), }
match will return a value:fn main() { let day = 4; let result = match day { 1 => "Monday", 2 => "Tuesday", 3 => "Wednesday", 4 => "Thursday", 5 => "Friday", 6 => "Saturday", 7 => "Sunday", _ => "Invalid day.", }; println!("{}", result); }
Loop
loop will create an infinite repeat:loop { println!("This will repeat forever!"); }
Use
break to stop the repeat:let mut count = 1; loop { println!("Hello World!"); if count == 3 { break; } count += 1; }
loop will return a value:let mut count = 1; let result = loop { println!("Hello!"); if count == 3 { break count; // Stop the loop and return the number 3 } count += 1; }; println!("The loop stopped at: {}", result);
While loop
let mut count = 1; while count <= 5 { println!("Count: {}", count); count += 1; }
For loop
fn main() { for i in 1..3 { println!("Number: {}", i); } /* Number: 1 Number: 2 */ for i in 1..=3 { println!("Number: {}", i); } /* Number: 1 Number: 2 Number: 3 */ }
1..3will iterate from 1 to 3 but not include3.
1..=3is the same as1..3, but it includes3
Use these in any loop:
break- stop the loop
continue- skip a value in the loop
Function
fn add(a: i32, b: i32) -> i32 { return a + b; } fn main() { let result = add(3, 2); println!("The Result is {}", result); }
Ownership
Ownership rules:
- Every value has one owner. (Usually, it is a variable)
- When the owner goes out of scope, the value is deleted.
- One value has only one owner at a time, but you can borrow it.
let a = String::from("Hello"); let b = a; // ownership shift // println!("{}", a); ❌ ERROR! println!("{}", b);
Simple types (numbers, characters, and booleans) are copied, not moved:
let a = 10; let b = a; println!("{}", a); // 10 println!("{}", b); // 10
Use
& to borrow the value:let a = String::from("Hello"); let b = &a; let c = &a; println!("{}", a); // Hello println!("{}", b); // Hello println!("{}", c); // Hello
Mutable borrow:
let mut a = String::from("Hello"); let b = &mut a; b.push_str(" World"); println!("{}", b); // Hello World
A value has only one mutable reference at a time:
let mut a = String::from("Hello"); let b = &mut a; b.push_str(" World"); // println!("{}", a); // ❌ cannot borrow `a` as immutable because it is also borrowed as mutable println!("{}", b); // Hello