Radosław Miernik
Open source? Embrace, understand, develop.
Because we have to learn somehow.
fn main() {
let number = 6;
if number % 3 == 0 {
println!("number is divisible by 3");
} else if number % 2 == 0 {
println!("number is divisible by 2");
} else {
println!("number is not divisible by 3, or 2");
}
}
fn main() {
let condition = true;
let number = if condition { 5 } else { 6 };
println!("The value of number is: {}", number);
}
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("The result is {}", result);
}
fn main() {
let a = [10, 20, 30, 40, 50];
let mut index = 0;
while index < 5 {
println!("the value is: {}", a[index]);
index += 1;
}
}
fn main() {
let a = [10, 20, 30, 40, 50];
for element in a {
println!("the value is: {}", element);
}
}
fn is_divisible_by(lhs: u32, rhs: u32) -> bool {
if rhs == 0 {
// Early return.
return false;
}
// No `return` not `;` here!
lhs % rhs == 0
}
fn add_one_v1 (x: u32) -> u32 { x + 1 }
let add_one_v2 = |x: u32| -> u32 { x + 1 };
let add_one_v3 = |x| { x + 1 };
let add_one_v4 = |x| x + 1 ;
let sum_of_squared_odd_numbers: u32 = (0..)
.map(|n| n * n)
.take_while(|&n_squared| n_squared < limit)
.filter(|&n_squared| n % 2 == 1)
.fold(0, |sum, n_squared| sum + n_squared);
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
}
struct Tweet {
username: String,
content: String,
reply: bool,
retweet: bool,
retweets: u32,
}
trait Summary {
fn summarize(&self) -> String;
}
impl Summary for Tweet {
fn summarize(&self) -> String {
format!("{}: {}", self.username, self.content)
}
}
// Later
tweet.summarize()
Ownership is Rust’s most unique feature and has deep implications for the rest of the language. It enables Rust to make memory safety guarantees without needing a garbage collector, so it’s important to understand how ownership works.
By Radosław Miernik