Skip to content

Instantly share code, notes, and snippets.

@luish
Last active August 4, 2016 12:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luish/58686a596d32d0a49d4c2b272ade483e to your computer and use it in GitHub Desktop.
Save luish/58686a596d32d0a49d4c2b272ade483e to your computer and use it in GitHub Desktop.
A few notes while learning a bit of Rust

So comparing Rust to Swift, we have:

Traits = protocols

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)
    }
}

Generics

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 };

Mutability

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

Enums

Very similar

enum BoardGameTurn {
    Move { squares: i32 },
    Pass,
}

let y: BoardGameTurn = BoardGameTurn::Move { squares: 1 };

Pattern matching

Looks better with the keyword match:

let x = 1;

match x {
    1 => println!("one"),
    2 => println!("two"),
    3 => println!("three"),
    _ => println!("anything"),
}

also with ranges

Similar to swift

let x = 1;

match x {
    1 ... 5 => println!("one through five"),
    _ => println!("anything"),
}

match guards

with if similar to Swift case where:

let x = 4;
let y = false;

match x {
    4 | 5 if y => println!("yes"),
    _ => println!("no"),
}

Optional types

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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment