So comparing Rust to Swift, we have:
struct Circle {
x: f64,
y: f64,
radius: f64,
}
trait HasArea {
fn area(&self) -> f64;
}
impl HasArea for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * (self.radius * self.radius)
}
}
Pretty much the same
struct Point<T> {
x: T,
y: T,
}
let int_origin = Point { x: 0, y: 0 };
let float_origin = Point { x: 0.0, y: 0.0 };
Same let
for immutable things, but let mut
instead of var
:
let x = 5;
x = 6; // error
let mut x = 5;
x = 6; // all right
Very similar
enum BoardGameTurn {
Move { squares: i32 },
Pass,
}
let y: BoardGameTurn = BoardGameTurn::Move { squares: 1 };
Looks better with the keyword match
:
let x = 1;
match x {
1 => println!("one"),
2 => println!("two"),
3 => println!("three"),
_ => println!("anything"),
}
Similar to swift
let x = 1;
match x {
1 ... 5 => println!("one through five"),
_ => println!("anything"),
}
with if
similar to Swift case where
:
let x = 4;
let y = false;
match x {
4 | 5 if y => println!("yes"),
_ => println!("no"),
}
Unwrapping works similarly with pattern matching (if let
/ while let
)
if let Some(x) = option {
foo(x);
} else {
bar();
}
or
match option {
Some(x) => { foo(x) },
None => {},
}
and also with while let
:
let mut v = vec![1, 3, 5, 7, 11];
while let Some(x) = v.pop() {
println!("{}", x);
}
There is an explicit method called .unwrap()
(similar to swift !
)
if option.is_some() {
let x = option.unwrap();
foo(x);
}