Exploring Rust



Exploring Rust

0 0


exploring-rust

My talk on exploring Rust

On Github yggie / exploring-rust

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

- or as I affectionately call it, the zero-sized struct

A unit-like struct

struct Foo { }
          
- as of Rust 1.8, this syntax is valid

Zero sized!

assert!(size_of::<Foo>() == 0)
          
- uses up no bytes, but gives the compiler plenty of information!

Stateless trait implementations

impl Bar for Foo {
    fn bar(&self) {
        // magic here
    }
}
          
- useful for implementations of traits that require no state
  • Struct implementations that don’t exist at runtime

Newtype pattern

- as described on the Rust book, it is really just a tuple struct with a single element - the name was borrowed from Haskell’s newtype

A tuple struct with one element!

struct FooBar(usize);
          

No memory overhead!

assert!(size_of::<FooBar>() == size_of::<usize>())
          
- it has no memory overhead, but a different type identity

Validated types

impl Vector {
    pub fn normalize(self) -> UnitVector {
        UnitVector::from(self)
    }
}
          
- useful to assert compile time guarantees that the type has some useful properties - also limits operations between the newtypes and ordinary types, unless the operations are defined (like Add/Sub impls)
  • 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;
    }
}
          
- complements the Trait system very well - highly composable
  • Zero memory composable layers of abstractions

Lifetime bound structs

std::cell::Ref

pub struct Ref<'b, T> where T: 'b + ?Sized {
    // some fields omitted
}
          
- reference types - acts much like a borrow

Projections

struct Polygon(Vec<Point>);

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

struct SubPolygon<'a>(Vec<&'a Point>);
          
- complex projections of the data onto simpler types - powerful abstraction without the cost of copying data
  • 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?

Exploring Rust