Exploring Rust

Background

  • Studied Mechanical Engineering
  • Short stint as a Mechanical Engineer
  • Now working as a Web Developer

I like Rust

Speed, Safety and Concurrency

Zero-cost abstractions

Traits

A simple trait


trait Foo {
    fn bar(&self);
}
          

Static dispatch


fn call_bar<T: Foo>(t: T) {
    t.bar()
}
          
  • Avoid dynamic dispatch (performance cost)

Unit-like structs

A unit-like struct


struct Foo { }
          

Zero sized!


assert!(size_of::<Foo>() == 0)
          

Stateless trait implementations


impl Bar for Foo {
    fn bar(&self) {
        // magic here
    }
}
          
  • Struct implementations that don’t exist at runtime

Newtype pattern

A tuple struct with one element!


struct FooBar(usize);
          

No memory overhead!


assert!(size_of::<FooBar>() == size_of::<usize>())
          

Validated types


impl Vector {
    pub fn normalize(self) -> UnitVector {
        UnitVector::from(self)
    }
}
          
  • Encode validations in the type system

Stateless decorators


struct LogFoo<T: Foo>(T);

impl<T: Foo> Foo for LogFoo<T> {
    fn bar(&self) -> Bar {
        let bar = self.0.bar();
        println!("result of foo: {:?}", bar);
        return bar;
    }
}
          
  • Zero memory composable layers of abstractions

Lifetime bound structs

std::cell::Ref


pub struct Ref<'b, T> where T: 'b + ?Sized {
    // some fields omitted
}
          

Projections


struct Polygon(Vec<Point>);

struct PolygonEdge<'a>(&'a Point, &'a Point);

struct SubPolygon<'a>(Vec<&'a Point>);
          
  • Create meaningful structs without copying

This slide is intentionally left blank

Useful links

Summary

  • Traits are awesome
  • Lifetimes are awesome
  • Rust is awesome

Any questions?