Share
Embed
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
Transcript
74 slides
-
About Me. 2 I am Vigneshwer AI Researcher Author of
Rust CookBook moz://a Techspeaker -
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 -
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 -
What is Rust? System programming language that has great control
like C/C++, delivers productivity like in Python, and is super safe -
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 -
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 ... -
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 -
Segmentation Fault ➔ Dereference a null pointer ➔ Try to
write to a portion of memory that was marked as read-only -
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 -
Installing Rust Ubuntu / MacOS • Open your terminal (Ctrl
+ Alt +T) • curl -sSf https://static.rust-lang.org/rustup.sh | sh -
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 -
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 -
30 Zero-cost abstractions Memory safety & data-race freedom + =
Confident, productive systems programming -
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++ -
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 -
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. -
36 “Manual” memory management in Rust: Values owned by creator.
Values moved via assignment. When final owner returns, value is freed. Feels invisible. ] -
~ Ownership and Borrowing ~ Type Ownership T Alias? Mutate?
Owned ✓ &T Shared reference ✓ -
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 -
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 -
~ Ownership and Borrowing ~ Type Ownership T &T Alias?
Mutate? Owned Shared reference ✓ ✓ &mut T Mutable reference ✓ -
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] -
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 -
‘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; -
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) -
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`” -
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? -
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 -
A bit complex example fn avg(list: &[f64]) -> f64 {
let mut total = 0; for el in list{ total += *el; } total/list.len() as f64 } -
HLL version fn avg(list: &[f64]) -> f64 { list.iter().sum::<f64>() /
list.len() as f64 } -
Parallel Version (Rayon) fn avg(list: &[f64]) -> f64 { list.par_iter().sum::<f64>()
/ list.len() as f64 } -
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 -
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) -
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) -
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 -
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) -
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) -
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) -
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) -
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 -
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 -
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) -
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) -
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