Skip to content

Instantly share code, notes, and snippets.

@optozorax
Last active April 29, 2020 09:56
Show Gist options
  • Save optozorax/dd4b6af9147834684841a3a2a4801e64 to your computer and use it in GitHub Desktop.
Save optozorax/dd4b6af9147834684841a3a2a4801e64 to your computer and use it in GitHub Desktop.
Advertising for Rust

Rust is awesome

Type names

let a: i32 = 1;
let b: f32 = 1.0;
let c: u8 = 255u8;
let d: i64 = 1_000_000i64;
let e: usize = "string".len();
let f: char = 'ы';

Tuple

let a = (1,);
assert_eq!(a.0, 1);
let a = (1, 1.0);
assert_eq!(a.0, 1);
assert_eq!(a.1, 1.0);
let a: (i32, i64, &str) = (1, 1.0, "1");
assert_eq!(a.0, 1);
assert_eq!(a.1, 1.0);
assert_eq!(a.2, "1");

let (b, _, c) = a;
assert_eq!(b, 1);
assert_eq!(c, "1");
struct Deg(f32);
let a = Deg(1.0);

struct Rad(f32);
let b = Rad(0.0);

struct Pair(f32, f32);
let c = Pair(0.0, 1.0);

Everything is expression

let a = if 1 < 2 { "string" } else { "another" };
let a = {
	let mut result = Vec::new();
	result.push(1);
	result.push(2);
	result.push(3);
	result
};
assert_eq!(a, vec![1, 2, 3]);
let mut counter = 0;

let result = loop {
	counter += 1;

	if counter == 10 {
		break counter * 2;
	}
};

assert_eq!(result, 20);
struct Tree {
	left: Option<Box<Tree>>,
	right: Option<Box<Tree>>,
}

let my_tree = Tree {
	left: Box::new(
		Tree {
			left: Box::new(
				Tree {
					left: None,
					right: None,
				}
			),
			right: None,
		}
	),
	right: Box::new(
		Tree {
			left: None,
			right: None,
		}
	),
};

Pattern matching

match number {
	1 => println!("One!"),
	2 | 3 | 5 | 7 | 11 => println!("This is a prime"),
	13..=19 => println!("A teen"),
	_ => println!("Ain't special"),
}
fn fib(n: i32) -> i32 {
	match n {
		0 => 1,
		1 => 1,
		_ => fib(n-1) + fib(n-2),
	}
}
let pair = (0, -2);
match pair {
	(0, y) => println!("First is `0` and `y` is `{:?}`", y),
	(x, 0) => println!("`x` is `{:?}` and last is `0`", x),
	_      => println!("It doesn't matter what they are"),
}
let pair = (2, -2);
match pair {
	(x, y) if x == y => println!("These are twins"),
	(x, y) if x + y == 0 => println!("Antimatter, kaboom!"),
	(x, _) if x % 2 == 1 => println!("The first one is odd"),
	_ => println!("No correlation..."),
}

Loop labels

'outer: loop {
	println!("outer");
	'inner: loop {
		println!("inner");
		break 'outer;
	}
}

Functional style + Iterators vs Imperative cycles

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;

    // Imperative approach
    // Declare accumulator variable
    let mut acc = 0;
    // Iterate: 0, 1, 2, ... to infinity
    for n in 0.. {
        // Square the number
        let n_squared = n * n;

        if n_squared >= upper {
            // Break loop if exceeded the upper limit
            break;
        } else if is_odd(n_squared) {
            // Accumulate value, if it's odd
            acc += n_squared;
        }
    }
    println!("imperative style: {}", acc);

    // Functional approach
    let sum_of_squared_odd_numbers: u32 =
        (0..).map(|n| n * n)                             // All natural numbers squared
             .take_while(|&n_squared| n_squared < upper) // Below upper limit
             .filter(|&n_squared| is_odd(n_squared))     // That are odd
             .sum();                                     // Sum them
    println!("functional style: {}", sum_of_squared_odd_numbers);
}

Enums

enum CStyle {
	Name1,
	Name2,
	Name3,
}

let a = CStyle::Name1;
let b = CStyle::Name1;

let c = match a {
	CStyle::Name1 => 1,
	CStyle::Name2 => 2,
	CStyle::Name3 => 3,
};
enum UnionLike {
	Float(f64),
	Int(i64),
	Fraction(i32, i32),
	NaN,
}

let a = UnionLike::Float(1.0);
let b = UnionLike::NaN;

let c = match a {
	Float(f) => format!("{}", f),
	Int(i) => format!("{}", i),
	Fraction(a, b) => format!("{}/{}", a, b),
	NaN => format!("NaN"),	
};

assert_eq!(c, String::from("1.0"));
enum WebEvent {
	// An `enum` may either be `unit-like`,
	PageLoad,
	PageUnload,
	// like tuple structs,
	KeyPress(char),
	Paste(String),
	// or c-like structures.
	Click { x: i64, y: i64 },
}

// A function which takes a `WebEvent` enum as an argument and
// returns nothing.
fn inspect(event: WebEvent) {
	match event {
		WebEvent::PageLoad => println!("page loaded"),
		WebEvent::PageUnload => println!("page unloaded"),
		// Destructure `c` from inside the `enum`.
		WebEvent::KeyPress(c) => println!("pressed '{}'.", c),
		WebEvent::Paste(s) => println!("pasted \"{}\".", s),
		// Destructure `Click` into `x` and `y`.
		WebEvent::Click { x, y } => {
			println!("clicked at x={}, y={}.", x, y);
		},
	}
}

Option, Result

enum Option<T> {
	Some(T),
	None,
}

let a = Some(1.0);
let b = None;
fn find(where: &[i32], what: i32) -> Option<i32> {
	for (index, i) in where.iter().enumerate() {
		if i == what {
			return Some(index);
		}
	}

	None
}

assert_eq!(find(&vec![1, 2, 3], 3), Some(2));
assert_eq!(find(&vec![1, 2, 3], 100), None);
enum Result<T, E> {
    Ok(T),
    Err(E),
}

let a = Ok(1.0);
let b = Err("can't parse");
fn parse_strings(strs: &[&str]) -> Result<Vec<i32>, String> {
	let mut result = Vec::new();
	for i in strs {
		match i.parse::<i32>() {
			Ok(number) => result.push(number),
			Err(_) => return Err(format!("can't parse string to number: {}", i)),
		}
	}

	Ok(result)
}

assert_eq!(parse_strings(&["1", "2", "3"]), Ok(vec![1, 2, 3]));
assert_eq!(parse_strings(&["1", "2", "ы"]), Err("can't parse string to number: ы".to_string()));

Traits and implementations

struct Point {
    x: f64,
    y: f64,
}

impl Point {
    // This is a static method
    // Static methods don't need to be called by an instance
    // These methods are generally used as constructors
    fn origin() -> Point {
        Point { x: 0.0, y: 0.0 }
    }

    // Another static method, taking two arguments:
    fn new(x: f64, y: f64) -> Point {
        Point { x: x, y: y }
    }

    fn len(&self) -> f64 {
    	(x*x + y*y).sqrt()
    }
}

let a = Point::origin();
let b = Point::new(1, 2);

let alen = a.len();
let blen = b.len();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment