Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Rust Workshop - Mozilla Hyderbad

Rust Workshop - Mozilla Hyderbad

The workshop content covers the all the important concepts that one needs to know about Rust Lang and comes with an extensive set of training materials which aims to provide a hand's on Rust programming experience to the participants.

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

Many of the slides in this deck are taken from the Rust keynote & my previous talk slides.

vigneshwer dhinakaran

December 01, 2017
Tweet

More Decks by vigneshwer dhinakaran

Other Decks in Programming

Transcript

  1. About Me. 2 I am Vigneshwer AI Researcher Author of

    Rust CookBook moz://a Techspeaker
  2. 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
  3. 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
  4. 9

  5. 10

  6. 11

  7. 12

  8. What is Rust? System programming language that has great control

    like C/C++, delivers productivity like in Python, and is super safe
  9. 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
  10. 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 ...
  11. 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
  12. Segmentation Fault ➔ Dereference a null pointer ➔ Try to

    write to a portion of memory that was marked as read-only
  13. 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
  14. Installing Rust Ubuntu / MacOS • Open your terminal (Ctrl

    + Alt +T) • curl -sSf https://static.rust-lang.org/rustup.sh | sh
  15. 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
  16. 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
  17. 30 Zero-cost abstractions Memory safety & data-race freedom + =

    Confident, productive systems programming
  18. Zero-cost abstractions void example() { vector<string> 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++
  19. void example() { vector<string> 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
  20. fn main() { let mut book = Vec::new(); book.push(…); book.push(…);

    publish(book); publish(book); } fn publish(book: Vec<String>) { … } 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.
  21. 36 “Manual” memory management in Rust: Values owned by creator.

    Values moved via assignment. When final owner returns, value is freed. Feels invisible. ]
  22. fn main() { let mut book = Vec::new(); book.push(…); book.push(…);

    let p = &book; publish(p); publish(p); } fn publish(book: &Vec<String>) { … } 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
  23. 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
  24. ~ Ownership and Borrowing ~ Type Ownership T &T Alias?

    Mutate? Owned Shared reference ✓ ✓ &mut T Mutable reference ✓
  25. fn main() { let mut book = Vec::new(); book.push(…); book.push(…);

    edit(&mut book); edit(&mut book); } fn edit(book: &mut Vec<String>) { book.push(…); } Mutable borrow Mutable reference to a vector 42 String book data length capacity [0] [1] book [2] Mutable borrow [3]
  26. 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
  27. ‘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;
  28. 45 fn first<‘a>(v: &’a Vec<String>) -> &’a String { return

    &v[0]; } “Returns a reference derived from `v`” fn first(v: &Vec<String>) -> &String { return &v[0]; } (more common shorthand)
  29. 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`”
  30. 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?
  31. 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
  32. A bit complex example fn avg(list: &[f64]) -> f64 {

    let mut total = 0; for el in list{ total += *el; } total/list.len() as f64 }
  33. 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
  34. 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)
  35. 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)
  36. 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
  37. 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)
  38. 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)
  39. 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)
  40. 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)
  41. 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
  42. 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
  43. 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)
  44. 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)
  45. 72

  46. 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