class: center, middle, ferris Introduction to Rust ==================== Wesley Moore ------------ ![Ferris the Rustacean animation](images/ferris.gif) --- # Agenda 1. Features 2. Tooling 3. Concepts 4. Demo 5. Questions --- # Introduction ```rust fn main() { println!("Rust Introduction"); } ``` > **Rust** is a systems programming language that runs blazingly fast, prevents > segfaults, and guarantees thread safety. — [rust-lang.org](https://www.rust-lang.org/) --- # Systems Programming Language * Compiles to native code. -- * Aims to solve the same sorts of problems that C and C++ are used to solve but with improved safety. -- * Also seeing use in: -- * Web (front and backend) -- * Operating systems ([Redox OS][redox]) -- * Embedded systems (microcontrollers) --- # Runs Blazingly Fast ![Benchmarks Chart](images/benchmarks.png) --- # Runs Blazingly Fast * No interpreter, no runtime. -- * Memory safety without garbage collection. -- * Zero cost abstractions. --- class: segfaults # Prevents Segfaults * No `nil`, `NULL` or other [billion dollar mistakes][billion-dollar-mistake]. ![undefined method for nil:NilClass](images/undefined-method-nil.png) This is not a thing. At all. Ever. .center[[billion-dollar-mistake]: https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare] --- # Guarantees Thread Safety * Strongly, statically typed with an emphasis on safety and correctness. -- * Ownership model tracks owner and lifetime of memory. -- * No data races: Compiler knows which thread owns what data. -- * This leads to, "[Fearless Concurrency][fearless-concurrency]". > Mozilla made two previous attempts to parallelize its style system in C++, > and both of them failed. But Rust’s fearless concurrency has made parallelism > practical! — [Fearless Concurrency in Firefox Quantum](https://blog.rust-lang.org/2017/11/14/Fearless-Concurrency-In-Firefox-Quantum.html) (Nov 2017) --- # Strong Static Type System * Do more at compile time so fewer tests and runtime checks are required. -- * Concepts mostly familiar. No need to learn an entirely new paradigm. -- * Traits and generics instead of objects and inheritance. -- * Type inference reduces the need to provide type annotations. -- * Refactor with impunity — even in large code bases. --- # Tooling Official distribution includes: `cargo` -- : * Build tool (no Makefiles) -- * Package manager (like bundler) -- * Test runner -- * Documentation generator --- ## Releases Generally managed with `rustup` -- : * Official toolchain manager (like rbenv) -- * New releases every 6 weeks * Committed to backwards compatibility in every release. --- class: crates # Crates * Rust favours a small, stable standard library. * Crates are the equivalent of Ruby gems. They are published to [crates.io](https://crates.io/). ![screenshot of crates.io](images/crates-io.png) --- # Community and Direction * RFC process. -- * Systematic improvement. -- * Emphasis on inclusion and building a friendly community. --- class: center, middle, bigger Concepts ======== --- # Functions ```rust fn add(left: i32, right: i32) -> i32 { left + right } fn main() { let sum = add(2, 3); } ``` --- # Conditionals: if ```rust let temperature: i32 = 29; if temperature > 25 { println!("Wesley is happy"); } else { println!("Too cold"); } ``` --- # Conditionals: match Can match structure and values: ```rust let month = "jan"; match month { "jan" => 1, "feb" => 2, "mar" => 3, "apr" => 4, "may" => 5, "jun" => 6, "jul" => 7, "aug" => 8, "sep" => 9, "oct" => 10, "nov" => 11, "dec" => 12, _ => panic!("invalid month"), }; ``` --- # Loops ```rust let numbers = [1, 2, 3]; for i in numbers.iter() { // do something } for i in 0..10 { // do something } ``` Also less frequently used commonly used `loop` and `while`. --- # Functional or Imperative ```rust fn variance_mean(data: &[f64], mean: f64) -> f64 { let mut sum = 0.; for d in data { sum += (d - mean).powf(2.0); } sum / data.len() as f64 } ``` Code from [hydromath] crate by Andrew MacDonald. --- # Functional or Imperative ```rust fn variance_mean(data: &[f64], mean: f64) -> f64 { data.into_iter() .map(|d| (d - mean).powf(2.0)) .sum::() / data.len() as f64 } ``` -- You pay _no cost_ for using the higher level style, it compiles to identical machine code (I checked). --- # enums Type that represents one possibility of several variants. Variants may optionally carry data. ```rust enum SerialProtocol { Usb, Rs485, Rs232, I2C, Spi, } ``` --- # structs Type that carries structured data. ```rust struct Person { name: String, age: i32, favourite_serial_protocol: SerialProtocol, } impl Person { fn name_and_age(&self) -> String { format!("{} is {} years old", self.name, self.age) } } ``` --- # Option Instead of `nil` and `NULL` there is `Option`. * Used to represent something that may be absent. ```rust enum Option { Some(T), None } ``` --- # Result When something can succeed or fail with an error. * There are no exceptions in Rust, `Result` is how you handle errors. ```rust enum Result { Ok(T), Err(E) } ``` --- Demo ==== Small tool that will determine a file's type from its extension: ```shell filetype src/main.rs somefile.rb ``` Should give output like: ``` Rust: src/main.rs Ruby: src/somefile.rb ``` --- class: center, middle, bigger Demo ==== --- class: center, middle, invert, bigger Questions? ========== --- Credits ======= * [Animated Ferris][animated-ferris] by A. L. Palmer, via [rustacean.net][rustacean]. * Portions of this talk were derived from [A Very Brief Intro to Rust][rust-intro] Copyright © 2016 Ashley Williams. * Benchmarks chart generated from data on [The Computer Language Benchmarks Game][benchmarks] on 10 Jan 2018. [rust-intro]: https://github.com/rustbridge/a-very-brief-intro-to-rust [animated-ferris]: https://www.behance.net/gallery/42774743/Rustacean [rustacean]: http://rustacean.net/ [fearless-concurrency]: https://doc.rust-lang.org/book/second-edition/ch16-00-concurrency.html [redox]: https://www.redox-os.org/ [hydromath]: https://github.com/amacd31/hydromath_rs [benchmarks]: https://benchmarksgame.alioth.debian.org/