Skip to content

Instantly share code, notes, and snippets.

@KodrAus
KodrAus / playground.rs
Last active August 21, 2016 10:29
Rust Generics
#[derive(Debug)]
struct Person<T> {
id: T,
title: String
}
impl <T> Person<T> {
fn new<I: Into<String>>(id: T, title: I) -> Self {
Person {
id: id,
@KodrAus
KodrAus / playground.rs
Created August 22, 2016 10:17
Rust Collections
fn main() {
//The vec! macro is sugar for inline Vec<T> building
let vec1 = vec!["a", "b", "c"];
let vec2 = vec![1, 2, 3];
//Rust has iterators, which are usually cheaper than looping
for (&x, &y) in vec1.iter().zip(vec2.iter()) {
println!("{}, {}", x, y);
}
@KodrAus
KodrAus / playground.rs
Created August 22, 2016 10:23
Rust Option
#[derive(Debug)]
struct Data;
//By default, variables must have a value
//Option<T> lets you explicitly bind to 'None'
fn might_be_null(input: bool) -> Option<Data> {
if input {
Some(Data)
}
else {
@KodrAus
KodrAus / playground.rs
Last active August 22, 2016 11:39
Rust Concurrency
use std::sync::{ Arc, RwLock };
use std::thread;
fn main() {
//Here we have an immutable array with mutable interior cells
//The length of the array can't change, but internal values can
//We use the Send sync variants for threading
let data = Arc::new(vec![
RwLock::new(1),
RwLock::new(2),
@KodrAus
KodrAus / playground.rs
Created August 22, 2016 11:09
Rust Crossbeam
extern crate crossbeam;
fn main() {
//Here we have a mutable array
let mut data = vec![1, 2, 3];
println!("{:?}", data);
//With crossbeam magic we can mutate this array concurrently without locks
//The crossbeam scope guarantees that the threads inside it will end before the scope does
@KodrAus
KodrAus / playground.rs
Created August 22, 2016 11:14
Rust Testing
#[test]
fn it_works() {
assert!(true);
}
@KodrAus
KodrAus / playground.rs
Created August 22, 2016 11:19
Rust Docs
//! # My Library
//!
//! This is a module-level doc comment.
//! Standard markdown is supported
/// This is a comment for an item.
///
/// Code samples are compiled and tested:
///
/// ```
@KodrAus
KodrAus / post.md
Created August 24, 2016 09:44
Gymnerics with Rust
@KodrAus
KodrAus / main.rs
Last active November 22, 2016 11:11
elastic_requests API
use std::borrow::Cow;
// Our wrapper types are basically a thin layer over a &str
macro_rules! wrapper {
($name:ident) => {
pub struct $name<'a>(pub Cow<'a, str>);
impl <'a> From<&'a str> for $name<'a> {
fn from(value: &'a str) -> $name<'a> {
$name(Cow::Borrowed(value))
@KodrAus
KodrAus / main.rs
Last active October 31, 2016 21:23
elastic API
// Our request type. Owned by someone else
trait Request {
fn url(&self) -> String;
}
trait IntoRequest<R> where R: Request {
fn into_request(self) -> R;
}
impl <R, I> IntoRequest<R> for I where