5. High level
fn is_odd(n: u32) -> bool {
n % 2 == 1
}
fn main() {
println!("Find the sum of all the squared odd numbers under 1000");
let upper = 1000;
let sum_of_squared_odd_numbers: u32 =
(0..).map(|n| n * n) // All natural numbers squared
.take_while(|&n| n < upper) // Below upper limit
.filter(|n| is_odd(*n)) // That are odd
.fold(0, |sum, i| sum + i); // Sum them
println!("result: {}", sum_of_squared_odd_numbers);
}
Gist
6. High level
• types
• type inference
• no manual memory management
• no null -> Option<T>
• no exception -> Result<T>
8. Abstraction without
overhead
let mut acc = 0;
// Iterate: 0, 1, 2, ... to infinity
for n in 0.. {
let n_squared = n * n;
if n_squared >= upper {
// Break loop if exceeded the upper limit
break;
} else if is_odd(n_squared) {
acc += n_squared;
}
}
acc
let sum_of_squared_odd_numbers: u32 =
(0..).map(|n| n * n)
.take_while(|&n| n < upper)
.filter(|n| is_odd(*n))
.fold(0, |sum, i| sum + i);
Same perf!
(functional version even faster)
9. Not OO but Struct with impl
struct Person {
name: String,
}
impl Person {
pub fn say_hello(&self) {
println!("{} says hello!", self.name);
}
}
fn main() {
let p = Person { name: "Bibi".to_string() };
p.say_hello();
}
Gist
10. Typeclasses
#[derive(Debug)]
struct Age {
age: i32,
}
fn main() {
let age1 = Age { age: 12 };
let age2 = Age { age: 24 };
let sum = age1 + age2;
println!("age1 + age2 = {:?}", sum);
}
<anon>:9:15: 9:19 error: binary operation `+` cannot be applied to type `Age` [E0369]
<anon>:9 let sum = age1 + age2;
^~~~
11. Typeclassesuse std::ops::Add;
#[derive(Debug)]
struct Age {
age: i32,
}
impl Add for Age {
type Output = Age;
fn add(self, other: Age) -> Age {
println!("Adding!");
Age { age: self.age + other.age }
}
}
fn main() {
let age1 = Age { age: 12 };
let age2 = Age { age: 24 };
let sum = age1 + age2;
println!("age1 + age2 = {:?}", sum);
}
Gist
15. Projects using Rust
• Servo
• Redox
• Firefox mp4
• Dropbox
But Go’s “memory footprint” was too
high for the massive storage systems
the company was trying to build.
Dropbox needed a language that
would take up less space in memory,
because so much memory would be
filled with all those files streaming
onto the machine. So, in the middle of
this two-and-half-year project, they
switched to Rust on the Diskotech
machines. And that’s what Dropbox is
now pushing into its data centers.