class: middle, home .home-left-column[ # The sweet flavour of
Rust
] .home-right-column[ .right[![The Rust](files/Rust_logo.png)] ] .footnote[ Introduction by Leonids Maslovs
http://leonardinius.github.io/sweet-slides.rs ] ??? Hello, My name is Leonids Maslovs and today I will introduce you into the beautiful and sweet world of Rust programming language. Quiz: - Who have tried/used Rust before? - Who have ever heard about Rust before? So, what's why I'm here today. --- class: about, middle .about-pull-left[![Wearing many hats](files/ManyHats.jpg)] .about-text[ ] .about-pull-right[![Galeo logo](files/galeo_logo_RGB.png)] .footnote[*.reference-url[http://profitablegrowth.com/wp-content/uploads/2010/01/ManyHats.jpg]] ??? A little note about myself. I'm in IT market for around 10 years now and during that period I used to wear different hats on: - starting from system administrator assistant - continuing to different development positions - and occasionally filling some kind of Architect, 'Archi'-type positions. At the moment I'm working with GaleoConsulting and my official job title is the "Lead technologist". --- class: middle, big-headers background-image: url(files/please-like-me.png) .contest-0[ ## Javascript? ] .contest-1[ ## Java? ] .contest-2[ ## Ruby? ] .contest-4[ ## Cobol? ] .footnote[*.reference-url[http://datedaily.mate1.com/wp-content/uploads/2013/09/please-like-me.png]] ??? Let's make a quick poll here. - Please raise your hands if you think Javascript is the most popular language in the world and will eat the world? Forest of hands - Java? Quite a lot - Ruby? Few, but still - Grandpa Cobol? No one, really. Why so? / O, one crazy guy from mainframe support team. So, - are we talking about the most trending programming language on the Github front page? - or the hottest job advertisement in Silicon Valley? No! We _are_ talking about it's _usage_ and _spread of use_. --- class: center, middle, big-headers, h-shadow # C/C++ ??? It's C/C++ and you know it. Surprise, surprise. It's _literally_, billions and billions lines of code running on billions and billions devices out there. It's running your bank systems, your smartphones, it's running in your car, your aircraft and nearby nuclear power station. It's almost everywhere to some extent or another. - How many of you had first hand experience with C or C++ in your professional life? Please raise your hands. - Did you enjoy it? - Was it painful? It certainly was to me. I specifically remember the pain and helplessness during my early experiments with C/C++. I was developing FAR Manager plugin with asynchronous file copy/move capabilities. And it struck me. At some point I was unable to reason about my code, it behaved unpredictably and would fail randomly. I guess, I might consider some tools, e.g. valgrind, but it was too advanced/unfamiliar to me at the time. _pause_ --- class: center, middle # C/C++ struggles? ??? Which brings us to C++ problems. - So, what's wrong with C/C++? --- class: h-last-highlighted ## - Manual memory management ??? - **Problems:** Manual and tedious process of resource allocation, inevitable mistakes, memory leaks and double frees. --- continued: true ## - Evil pointers ??? - C/C++ force you do manual pointer arithmetics, combined with manual memory allocation and type system we get: **Problems:** dangling pointers, NULL pointer dereference, use after free. --- continued: true ## - Weak concurrency models ??? - Concurrency in general is hard. C/C++ give you no built-in capabilities or machinery to simplify reasoning about concurrency, to avoid and catch most of the common problems early on, though API restrictions or compilation errors, not during execution in production. **Problems:** race conditions, deadlocks. Remember, the best way to fix production problem - is to prevent it from happening in the first place. --- class: center # C++11/14 .realistic-criteria-img[ ![Realistic criteria](files/xkcd-realistic-criteria.png) ] .footnote[*.reference-url[http://xkcd.com/1232/]] ??? Some of you will tell - "Hold on a second. What about C++11/14 standards? Don't they do all possible to address those issues?" C/C++ has the advantage of billions lines of existing and working source code out there, but it also means the backward compatibility is a MUST. The only way of moving forward is to extend language, making it more complex, more difficult to understand, yet not solving existing problems completely, but just adding safety nets around them.. So, they definitely do their best, but is it realistic to expect breaking and radical improvements any time soon? Could you wait that long? And some of the big players don't. They feel the pain on daily basis, either via vast amount of bug reports, or via slow and tedious release cycle. They don't want loose competitive advantage because of that and they are ready to go out and break status quo. --- class: medium layout: false .center[ ### Mozilla strikes back ] .left-column[ \- Unix, time-shared OS
\> _ASM, C_ \- Desktop as commodity, applications
\> _C/C++, Java_ \- Web
\> _PHP, Python, Java, .Net_ \- **Smartphone**
\> _**Java, Object-C, Swift**_ \- **Mobile (battery), Internet of Things**
\> **_C/C++, Go, ???_** ] .right-column[ ![Firefox](files/Browser-Firefox-Icon-Black.jpg) ![Mozilla](files/mozilla_wordmark_small.png) ] ??? And Mozilla strikes back. Mozilla _definitely_ is one of such market player. They are enormous organization with enormously large code bases, most of which are in fact C/C++ code bases, which still tries and delivers innovative stuff in short cycles. _But, they want to be even better!_ Let's not forget that Mozilla develops solutions (e.g. browser, Firefox OS, et cetera) running on mobile platforms and is also aiming at emerging Internet of Things market. It's niche of the low-level, system programming languages. Because battery life, every memory bit and every CPU cycle matters. _pause_ --- class: h-shadow .sweet-center[ # Rust ] .sweet-right-column[ ## **S**afe ## **W**orldly ## **E**fficient ## **E**xtensible ## **T**yped ] ??? And Mozilla decides to back up new, promising, low-level, system programming language - _Rust_. And while the official opening line is: - _"Rust is a systems programming language pursuing the trifecta: safe, fast, and concurrent."_ I, personally, find Rust very _SWEET_. _Read keywords from the slide_ --- ## Safe ### - Memory safety, no wild pointers ### - Typestate system, no null pointers ### - Mutability control, immutable by default ### - Side-effect control, pure by default ??? On _NULL pointers_: - Tony Hoare introduced `Nullable types` in Algol in 1965. - And it later described it as "billion dollar mistake". - We don't want that in our code, we don't want to repeat the same mistakes all over again. So, Rust team went different way: ... The compiler will do all possible and even more to save you from errors and even from yourself. You still could break the rules if you want it, but you have to do it intentionally and explicitly. --- ## Worldly ### -
GC, green threads, stack unwinding
### - Minimal, yet detachable runtime ### - C bindings / FFI ### - Cross compile ??? Worldly, or Pragmatic. Rust is pursuing generic, low-level system programming language agenda, and there is not place in language core for things like GC, green threads or C++/Java type exceptions with stack unwinding. Ironically enough, all of this _was_ initially included in the language, however.. One the things I admire Rust team for, they have guts and will to take a step back, take a deeper look, remove the noise and start it all over again. So, what the Rust is then? Rust is lightweight, with minimal, detachable core, effective C bindings and cross compile capabilities. Because every memory bit and every CPU cycle matters. --- ## Efficient ### - Zero-cost abstractions ### - LLVM type and level of optimizations ??? Usually speed and safety come in balance. You get one, you loose the other. You either do check array boundaries in runtime (and loose speed), or you do not (and loose safety). But not with Rust. Rust team takes different approach: - Memory safety must never be compromised. - Abstraction should be zero-cost, while still maintaining safety. - Practicality is key. They found a way to enforce safety during compile time, to stay both safe and efficient. You don't have to compromise. You still can have your cake and eat it too. --- ## Extensible ### - Linters ### - Hygienic macros ### - Plugins ??? It's an advanced topic and I will cover it very briefly. Few samples: - Code linters checking your code conforms to best practices - Hygienic (compile time checked) macroses checking SQL queries are valid during compilation time, not during execution et cetera. - Plugins integrating your DSLs with compiler. Basically, Rust is giving you best things of Lisp / Groovy / Javascript and still staying low-level, system programming language. --- ## Typed ### - Not "everything is an object" ### - Multi-paradigm: Structs, Traits ### - Trait-based generics, Type inference, Pattern matching ??? Rust is "close to metal", "Not everything is an object" programming language. Still, it features rich Type system, starting from simpler slices, tuples, structs, up to Typed enums and Trait based inheritance. But not only that, it also gives you some bells and whistles in the form of type inference, trait-based generics and pattern matching. It's system programming language, it's low level. It doesn't mean it should be inconvenient and hard to deal with. _pause_ --- class: center, middle, h-shadow ## println!("Code time"); --- class: center, middle ## Safety --- class: middle ```C int main(void) { char *s = "hello world"; *s = 'H'; } ``` ??? C unsafe / const --- class: middle ``` $ make hello && ./hello cc hello.c -o hello *[1] 6015 segmentation fault ./hello ``` --- class: middle ```rust fn main() { let s = &"hello world"; *s = "H"; } ``` ??? Rust --- class: middle ``` $ rustc hello.rs *hello.rs:3:5: 3:13 error: cannot assign to immutable borrowed * content '*s' *hello.rs:3 *s = "H"; * ^~~~~~~~ error: aborting due to previous error ``` --- class: middle ```cpp #include
#include
#include
int main() { std::vector
v; v.push_back("Hello"); std::string& x = v[0]; v.push_back("world"); std::cout << x; } ``` ??? C++ --- class: middle ``` $ make hello && ./hello g++ hello.cpp -o hello *[1] 8923 segmentation fault ./hello ``` --- class: middle ```rust fn main() { let mut v = vec![]; v.push("Hello"); let w = &v[0]; v.push("world"); println!("{} world", w); } ``` ??? Rust --- class: middle ``` $ rustc v-borrow.rs *v-borrow.rs:8:5: 8:6 error: cannot borrow 'v' as mutable because it * is also borrowed as immutable *v-borrow.rs:8 v.push("world"); * ^ *v-borrow.rs:6:14: 6:15 note: previous borrow of 'v' occurs here; * the immutable borrow prevents subsequent moves or * mutable borrows of 'v' until the borrow ends *v-borrow.rs:6 let w = &v[0]; * ^ *v-borrow.rs:11:2: 11:2 note: previous borrow ends here *v-borrow.rs:1 fn main() { *... *v-borrow.rs:11 } * ^ error: aborting due to previous error ``` --- class: center, middle ## Concurrency --- class: middle ```rust use std::thread; fn main() { for _ in 0..5 { thread::scoped(|| { println!("Hello, world!"); }); }; } ``` ??? Rust --- class: middle ```rust use std::thread; use std::sync::mpsc; use std::sync::mpsc::*; fn main() { let (tx, rx): (Sender
, Receiver
) = mpsc::channel(); let thread_tx = tx.clone(); thread::spawn(move || { thread_tx.send(10).ok().expect("Unable to send message"); }); println!("{:?}", rx.recv()); } ``` ??? Rust, channels --- class: center, middle ## Safety & Concurrency --- class: middle ```rust fn main() { let mut numbers = vec![1, 2, 3]; for _ in 0..3 { std::thread::scoped(move || { for j in 0..3 { numbers[j] += 1 } }); } } ``` ??? Rust --- class: middle ``` $ rustc borrow.rs *borrow.rs:6:29: 6:36 error: capture of moved value: 'numbers' *borrow.rs:6 for j in 0..3 { numbers[j] += 1 } * ^~~~~~~ *borrow.rs:5:34: 7:10 note: 'numbers' moved into closure environment * here because it has type '[closure(())]', which is * non-copyable *borrow.rs:5 std::thread::scoped(move || { *borrow.rs:6 for j in 0..3 { numbers[j] += 1 } *borrow.rs:7 }); *borrow.rs:5:34: 7:10 help: perhaps you meant to use 'clone()'? *borrow.rs:5 std::thread::scoped(move || { *borrow.rs:6 for j in 0..3 { numbers[j] += 1 } *borrow.rs:7 }); ``` --- class: middle ```rust use std::thread; use std::sync::{Arc,Mutex}; fn main() { let data = Arc::new(Mutex::new( vec![0;5] )); (0..5).map(|i| { let mutex = data.clone(); thread::scoped(move || { let mut vec = mutex.lock().unwrap(); vec[i] += 1; }) }).collect::
>(); println!("{:?}", *data.lock().unwrap()); } ``` --- class: center, middle ![chef](files/chef.png) ![icing on the cak](files/icing.png) ## Sweet, sweet Rust .footnote[.reference-url[\*http://images.profileengine.com/large/439245567/icing.on.the.cake,
\*https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xap1/v/t1.0-1/p160x160/1150317_10152149624495620_1605929745_n.png]] --- class: middle ```rust fn main() { let x = 5; match x { 1 | 2 => println!("one or two"), 3 => println!("three"), e @ 1...5 => println!("one through five, {}", e), e if e < 10 => println!("less than 10, {}", e), _ => println!("anything"), } } ``` ??? Rust --- class: middle ```rust use std::iter::iterate; fn main() { let fibonacci = iterate((0u32, 1u32), |e| {(e.1, e.0 + e.1)}) .skip(1) .map(|e| e.1); let numbers: Vec<_> = fibonacci.take(10).collect(); println!("{:?}", numbers); } ``` ??? Rust --- class: middle ```rust extern mod active_support; use active_support::Period; fn main() { println!("{:?}", 2.days().from_now()); println!("{:?}", 2.weeks().from_now()); println!("{:?}", 2.months().from_now()); println!("{:?}", 2.years().from_now()); } ``` ```rust pub trait Period { fn days(&self) -> TimeChange; fn weeks(&self) -> TimeChange; ... } impl Period for u32 { fn days(&self) -> TimeChange { TimeChange::new().days(*self as f32) } ... } ``` ??? Rust --- class: center, middle, h-shadow # Problems ??? - 1.0 Relese on my BD, on 15th of May - Unstable, API still change - No large track of use in production, duuh, obviously - It takes some time to get used to Rust concepts: borrowing, lifetimes etc ... --- ### Introductions #### - 30 min introduction into Rust http://doc.rust-lang.org/nightly/intro.html #### - Guide, Introduction Book http://doc.rust-lang.org/book/ #### - Rust by Example http://rustbyexample.com/ #### - Rust for CXX programmers https://github.com/rust-lang/rust/wiki/Rust-for-CXX-programmers http://www.quora.com/What-do-C-C++-systems-programmers-think-of-Rust --- ### Discussions / News #### - User forum http://users.rust-lang.org/ #### - Reddit /r/rust http://www.reddit.com/r/rust/ #### - \#rust on irc.mozilla.org https://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust #### - This Week in Rust http://this-week-in-rust.org/ --- class: center ## Try Rust online ## https://play.rust-lang.org/ --- class: center, middle, inverse, h-shadow # Thank you