Rust#
Rust is a modern compiler language that focueses on performance, reliability, and productivity. It is syntactically similar to C++, but is designed to provide better memory safety.
// hello beer: drink 0.5 l in 4 rounds
use std::{thread, time};
const LITER_PER_SIP: f32 = 37e-3;
fn sips2liter( num_sips: i32 ) -> f32 {
return (num_sips as f32) * LITER_PER_SIP;
}
fn main(){
let mut beer_l = 0.5;
let rounds = 4;
let sips_per_round = vec![3, 7, 4, 2];
println!("I drink {} l in {} rounds:", beer_l, rounds);
for sips in sips_per_round {
println!("I drink {} sips.\n", sips);
//thread::sleep( time::Duration::from_secs(sips) );
beer_l = beer_l - sips2liter( sips as i32 );
if beer_l <= 0.0 {
println!("My beer is empty!");
break
} else {
println!("I have {} l beer left.", beer_l);
}
}
}
Run your own program at the Rust Playground!
Important Basics#
- blocks of code delimited by curly brackets
{ }
- Cargo, the package manager, reads the
Cargo.toml
file, which contains details and dependencies for every project. - memory safety: Data values can only be initialized by a fixed set of forms and the inputs must be already initialized.
- resources are managed through the resource acquisition is initialization (RAII) convention, with optional reference counting.
- Rust has an ownership system where all values have a unique owner
Types#
- Integer:
ì8
,i16
,ì32
,u8
,u16
,u32
- Float:
f32
,f64
- String:
char
,str
- Collections:
array
,tuple
,slice
- Misc:
bool
,isize
,usize
let tuple = ("hello", 5, 'c');
assert_eq!(tuple.0, "hello"); // tuples are accessed with .
Differences to common languages#
Control Flow#
- Assignment
let answer = "hello".to_string();
- Conditions
if i == 0 { } else { }
- Loops
for i in 0..5 { }
match
instead of switch
#
match number {
1 => println!("One!"), // Match a single value
3 | 5 | 7 | 9 => println!("Odd"), // Match several values
13...19 => println!("A teen"), // Match an inclusive range
_ => println!("Ain't special"), // Handle the rest of cases
}
Objects: traits
and impl
#
Similar to C, Rust uses struct
for data structures. Rust defines
trait
as an interface and impl
as an implementation of an interface
for a struct
.
trait Quack {
fn quack(&self);
}
struct Duck (){
name: String;
}
impl Quack for Duck {
fn quack(&self) {
println!("quack!");
}
}
trait Show {
fn show(&self) -> String;
}
impl Show for i32 {
fn show(&self) -> String {
format!("four-byte signed {}", self)
}
}
impl Show for f64 {
fn show(&self) -> String {
format!("eight-byte float {}", self)
}
}
References#
- Steve Donovan: A Gentle Introduction To Rust, 2018
- Rust Documentation