Slide 1

Slide 1 text

Hacker's guide to Rust Programming

Slide 2

Slide 2 text

About Me. 2 I am Vigneshwer AI Researcher Author of Rust CookBook moz://a Techspeaker

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

Objective 4 Core concepts of Rust Lang - Ownership & borrowing - Struct & Traits Community Details - Tool & Library Ecosystem - Scope of Rust Learn to build real world applications - FFI integrations - Implementing web services

Slide 5

Slide 5 text

Workshop Overview Core Concepts 1. Ownership & Borrowing Concept 2. Common Bugs 3. Memory Safety 4. Rust tools, library & community support ecosystem 5 Building real-world Apps in Rust 1. Web services in Rust 2. FFI examples Hand’s on experience with Rust Lang 1. Std Data types 2. Struct & Traits 3. Cargo features 4. Crates & Modules 5. Macro

Slide 6

Slide 6 text

where are we with Rust?

Slide 7

Slide 7 text

No content

Slide 8

Slide 8 text

No content

Slide 9

Slide 9 text

9

Slide 10

Slide 10 text

10

Slide 11

Slide 11 text

11

Slide 12

Slide 12 text

12

Slide 13

Slide 13 text

13 Photo credit: Salim Virji https://www.flickr.com/photos/salim/8594532469/ Safety = Eat your spinach!

Slide 14

Slide 14 text

14 Gradual adoption works.

Slide 15

Slide 15 text

2016 -17 Rust is the Most Loved Language by Developers

Slide 16

Slide 16 text

Friends of Rust Organizations running Rust in production. (https://www.rust-lang.org/en-US/friends.html)

Slide 17

Slide 17 text

What is Rust? System programming language that has great control like C/C++, delivers productivity like in Python, and is super safe

Slide 18

Slide 18 text

1 What Rust has to offer Strong safety guarantees… No seg-faults, no data-races, expressive type system. …without compromising on performance. No garbage collector, no runtime. Goal: Confident, productive systems programming

Slide 19

Slide 19 text

Why should one consider Rust? ➔ State of art programming language ➔ Solves a lot of common system programming bugs ➔ Cargo : Rust Package manager ➔ Improving your toolkit ➔ Self learning ➔ It's FUN ...

Slide 20

Slide 20 text

Basic Terminologies ➔ Low and high level language ➔ System programming ➔ Stack and heap ➔ Concurrency and parallelism ➔ Compile time and run time ➔ Type system ➔ Garbage collector ➔ Mutability ➔ Scope

Slide 21

Slide 21 text

Segmentation Fault ➔ Dereference a null pointer ➔ Try to write to a portion of memory that was marked as read-only

Slide 22

Slide 22 text

Buffer OverFlow ➔ Writing and reading the past end of buffer

Slide 23

Slide 23 text

Sample Error Outputs ➔ Segmentation fault ➔ Buffer OverFlow

Slide 24

Slide 24 text

No content

Slide 25

Slide 25 text

Hack without Fear ➔ Strong type system ◆ Reduces a lot of common bugs ➔ Borrowing and Ownership ◆ Memory safety ◆ Freedom from data races ➔ Abstraction without overhead ➔ Stability without stagnation ➔ Libraries & tools ecosystem

Slide 26

Slide 26 text

Installing Rust Ubuntu / MacOS ● Open your terminal (Ctrl + Alt +T) ● curl -sSf https://static.rust-lang.org/rustup.sh | sh

Slide 27

Slide 27 text

Installing Rust rustc --version cargo --version Windows : ● Go to https://win.rustup.rs/ ○ This will download rustup-init.exe ● Double click and start the installation

Slide 28

Slide 28 text

Features of rustup tool -> Update to latest version: rustup update stable -> Update the rustup tool to the latest version rustup self update -> Install the nightly toolkit version of the Rust compiler: rustup install nightly -> Change the default version of the Rust compiler to nightly version: rustup default nightly

Slide 29

Slide 29 text

29 Photo credit: Amelia Wells https://www.flickr.com/photos/speculummundi/6424242877/ Memory safety

Slide 30

Slide 30 text

30 Zero-cost abstractions Memory safety & data-race freedom + = Confident, productive systems programming

Slide 31

Slide 31 text

Zero-cost abstractions void example() { vector vector; … auto& elem = vector[0]; … } string [0] … elem vector data length capacity [0] [n] […] … ‘H’ … ‘e’ Stack and inline layout. Lightweight references Deterministic destruction Stack Heap C++

Slide 32

Slide 32 text

void example() { vector vector; … auto& elem = vector[0]; vector.push_back(some_string); cout << elem; } vector data length capacity [0] … [0] [1] elem Aliasing: more than one pointer to same Dangling pointer: pointer to freed memory. Mutating the vector freed old contents. C++ Memory safety

Slide 33

Slide 33 text

~ Ownership and Borrowing ~ Type Ownership Alias? Mutate? T Owned ✓

Slide 34

Slide 34 text

Ownership n. The act, state, or right of possessing something. 34

Slide 35

Slide 35 text

fn main() { let mut book = Vec::new(); book.push(…); book.push(…); publish(book); publish(book); } fn publish(book: Vec) { … } Ownership Take ownership of the vector 35 Error: use of moved value: `book` String book data length capacity [0] [1] data length capacity ~~~~~~~~~~~ Give ownership.

Slide 36

Slide 36 text

36 “Manual” memory management in Rust: Values owned by creator. Values moved via assignment. When final owner returns, value is freed. Feels invisible. ]

Slide 37

Slide 37 text

Borrow v. To receive something with the promise of returning it. 37

Slide 38

Slide 38 text

~ Ownership and Borrowing ~ Type Ownership T Alias? Mutate? Owned ✓ &T Shared reference ✓

Slide 39

Slide 39 text

fn main() { let mut book = Vec::new(); book.push(…); book.push(…); let p = &book; publish(p); publish(p); } fn publish(book: &Vec) { … } Shared borrow Change type to a reference to a vector 39 String book data length capacity [0] [1] Borrow the vector, creating a reference p book

Slide 40

Slide 40 text

cannot mutate while shared 40 Shared data: immutable let mut book = Vec::new(); book.push(…); { let r = &book; book.push(…); r.push(…); } book.push(…); book mutable here ~~~~~~~~~~~ book borrowed here ~~~~~~~~~ * Actually: mutation only under controlled circumstances * now book is mutable again r goes out of scope; borrow ends

Slide 41

Slide 41 text

~ Ownership and Borrowing ~ Type Ownership T &T Alias? Mutate? Owned Shared reference ✓ ✓ &mut T Mutable reference ✓

Slide 42

Slide 42 text

fn main() { let mut book = Vec::new(); book.push(…); book.push(…); edit(&mut book); edit(&mut book); } fn edit(book: &mut Vec) { book.push(…); } Mutable borrow Mutable reference to a vector 42 String book data length capacity [0] [1] book [2] Mutable borrow [3]

Slide 43

Slide 43 text

cannot access while borrowed but &mut ref can mutate 43 Mutable references: no other access let mut book = Vec::new(); book.push(…); { let r = &mut book; book.len(); r.push(…); } book.push(…); book mutable here ~~~~~~~~~ book borrowed here borrow ended; accessible again r goes out of scope; borrow ends

Slide 44

Slide 44 text

‘l 44 Lifetime of a reference let mut book = Vec::new(); … { let r: &String = &book[0]; … } let r: &String = &book; let r: &’l String = &book;

Slide 45

Slide 45 text

45 fn first<‘a>(v: &’a Vec) -> &’a String { return &v[0]; } “Returns a reference derived from `v`” fn first(v: &Vec) -> &String { return &v[0]; } (more common shorthand)

Slide 46

Slide 46 text

46 const git_tree_entry * git_tree_entry_byname(const git_tree *tree, const char *filename); This returns a git_tree_entry that is owned by the git_tree. You don't have to free it, but you must not use it after the git_tree is released. impl Tree { fn by_name<‘a>(&’a self, filename: &str) -> &’a TreeEntry { .. } } “Returns a reference derived from `self`”

Slide 47

Slide 47 text

impl Tree { fn by_name<‘a>(&’a self, filename: &str) -> &’a TreeEntry { .. } } 47 const git_tree_entry * git_tree_entry_byname(const git_tree *tree, const char *filename); This returns a git_tree_entry that is owned by the git_tree. You don't have to free it, but you must not use it after the git_tree is released. Borrowed string Does not escape `by_name` Immutable while `by_name` executes Read-only, yes, but mutable through an alias? Will `git_tree_entry_byname` keep this pointer? Start a thread using it?

Slide 48

Slide 48 text

2nd Stop Core Concepts 1. Ownership & Borrowing Concept 2. Common Bugs 3. Memory Safety 4. Rust tools, library & community support ecosystem 48 Building real-world Apps in Rust 1. Web services in Rust 2. FFI examples Hand’s on experience with Rust Lang 1. Std Data types 2. Struct & Traits 3. Cargo features 4. Crates & Modules 5. Macro

Slide 49

Slide 49 text

A bit complex example fn avg(list: &[f64]) -> f64 { let mut total = 0; for el in list{ total += *el; } total/list.len() as f64 }

Slide 50

Slide 50 text

HLL version fn avg(list: &[f64]) -> f64 { list.iter().sum::() / list.len() as f64 }

Slide 51

Slide 51 text

Parallel Version (Rayon) fn avg(list: &[f64]) -> f64 { list.par_iter().sum::() / list.len() as f64 }

Slide 52

Slide 52 text

Demos https://github.com/vigneshwerd/MozillaHyd-Rust-Workshop

Slide 53

Slide 53 text

Demos ➔ Vectors, Pointers, closures, typecasting ➔ Complex Data Structures : Structs, enum, impl , trait ➔ Decision making and looping statements ➔ Crates and Modules ➔ Cargo features ➔ Introduction to Rust library ecosystem ➔ Error handling ➔ Understanding Macros ➔ FFI Examples ➔ Building REST API’s

Slide 54

Slide 54 text

Vectors & Std datatypes ➔ Sample arithmetic operations (arithmetic.rs) ➔ Arrays (array.rs) ➔ Assignment operations (assignment.rs) ➔ Boolean types (boolean.rs) ➔ Calculator example (calculator.rs) ➔ Decimal (decimal.rs) ➔ Mutability example (mutuable.rs) ➔ String operations (string.rs) ➔ Tuples (tuple.rs) ➔ Vector (vector.rs)

Slide 55

Slide 55 text

User defined structs, Pointers, closures, typecasting ➔ Closure (closures.rs) ➔ Conditions (condition.rs) ➔ Constants (constant.rs) ➔ Enum types (enum.rs) ➔ block example (expressions.rs) ➔ Looping (looping.rs) ➔ Pointer example (pointers.rs) ➔ struct operations (string.rs) ➔ Methods (implement.rs) ➔ Functionality (trait.rs) ➔ Typecasting (typecasting.rs)

Slide 56

Slide 56 text

Cargo Features ➔ Creating a project ➔ Building & Running a project ➔ Installing dependencies ➔ Deployment of projects ➔ Publishing a package to crates.io ➔ Testing and benchmarking ➔ CI using travis CI

Slide 57

Slide 57 text

Crates and Modules ➔ Defining a module in Rust (sample_mod.rs) ➔ Building a nested module (sample_nested.rs) ➔ Creating a module with struct (sample_struct.rs) ➔ Controlling modules (sample_control.rs) ➔ Accessing modules (sample_access.rs) ➔ Creating a file hierarchy (sample_split.rs) ➔ Building libraries in Rust (sample_lib.rs) ➔ Calling external crates (sample_exec.rs)

Slide 58

Slide 58 text

Deep Dive into Parallelism ➔ Creating a thread in Rust (sample_move.rs) ➔ Spawning multiple threads (sample_multiple_thread.rs) ➔ Holding threads in a vector (sample_thread_expt.rs) ➔ Sharing data between threads using channels (sample_channel.rs) ➔ Implementing safe mutable access (sample_lock.rs) ➔ Creating child processes (sample_child_process.rs) ➔ Waiting for a child process (sample_wait.rs) ➔ Making sequential code parallel (sample_rayon.rs)

Slide 59

Slide 59 text

Efficient Error Handling ➔ Implementing panic (sample_panic.rs) ➔ Implementing Option (sample_option.rs) ➔ Creating map combinator (sample_map.rs) ➔ Creating and_then combinator (sample_and_then.rs) ➔ Creating map for the Result type (sample_map_results.rs) ➔ Implementing aliases (sample_alias.rs) ➔ Handling multiple errors (sample_multi_err.rs) ➔ Implementing early returns (sample_erl_ret.rs) ➔ Implementing the try! Macro (sample_try.rs)

Slide 60

Slide 60 text

Hacking Macros ➔ Building macros in Rust (sample_macro.rs) ➔ Implementing matching in macros (sample_match.rs) ➔ Implementing designators (sample_designator.rs) ➔ Overloading macros (sample_overloading.rs)

Slide 61

Slide 61 text

Last stop for the day Core Concepts 1. Ownership & Borrowing Concept 2. Common Bugs 3. Memory Safety 4. Rust tools, library & community support ecosystem 61 Building real-world Apps in Rust 1. Web services in Rust 2. FFI examples Hand’s on experience with Rust Lang 1. Std Data types 2. Struct & Traits 3. Cargo features 4. Crates & Modules 5. Macro

Slide 62

Slide 62 text

Integrating Rust with other languages ➔ Calling C operations from Rust ➔ Calling Rust commands from C ➔ Calling Rust operations from Node.js apps ➔ Calling Rust operations from Python ➔ Writing a Python module in Rust

Slide 63

Slide 63 text

Web Development with Rust ➔ Setting up a web server (nickel-demo) ➔ Creating endpoints (nickel-routing) ➔ Handling JSONRequests (nickel-jsonhandling) ➔ Building a custom error handler (nickel-errorhandling) ➔ Hosting templates (nickel-template)

Slide 64

Slide 64 text

RESTful API web service ➔ Setting up the API (sample_app) ➔ Saving user data in MongoDB (sample_post) ➔ Fetching user data (sample_get) ➔ Deleting user data (sample_rest_api)

Slide 65

Slide 65 text

Get /users

Slide 66

Slide 66 text

Post /users/new

Slide 67

Slide 67 text

DELETE /users/object_id

Slide 68

Slide 68 text

68 Community Photo credit: David McSpadden https://www.flickr.com/photos/familyclan/15535822737/

Slide 69

Slide 69 text

69 From http://jvns.ca/blog/2016/09/11/rustconf-keynote/ Open and welcoming

Slide 70

Slide 70 text

70 Almost 40 working groups spread across 7 Rust “teams”

Slide 71

Slide 71 text

71 RFC Process

Slide 72

Slide 72 text

72

Slide 73

Slide 73 text

Rust Trailheads Follow us on Twitter: @rustlang @ThisWeekInRust Join Rust IRC Channels: #rust #rust-community #rust-machine-learning #tensorflow-rust Join Rust Websites: rust-lang.org rustbyexample.com rustaceans.org reddit.com/r/rust/ 73

Slide 74

Slide 74 text

Thanks! 74 Twitter @dvigneshwer Instagram @dvigneshwer Email [email protected] Website dvigneshwer.github.io/