Concepts of programming languages Rust Floris Schild, Mats - - PowerPoint PPT Presentation

concepts of programming languages
SMART_READER_LITE
LIVE PREVIEW

Concepts of programming languages Rust Floris Schild, Mats - - PowerPoint PPT Presentation

[ Faculty of Science Information and Computing Sciences] 1 Concepts of programming languages Rust Floris Schild, Mats Veldhuizen, Ruben Schenkuizen, Tobias van Driessel, Tom Freijsen [ Faculty of Science Information and Computing Sciences] 2


slide-1
SLIDE 1

[Faculty of Science Information and Computing Sciences] 1

Concepts of programming languages

Rust

Floris Schild, Mats Veldhuizen, Ruben Schenkuizen, Tobias van Driessel, Tom Freijsen

slide-2
SLIDE 2

[Faculty of Science Information and Computing Sciences] 2

slide-3
SLIDE 3

[Faculty of Science Information and Computing Sciences] 3

Presentation Schedule

▶ Background ▶ Design principles ▶ What problems does Rust solve and how? ▶ Practical details

slide-4
SLIDE 4

[Faculty of Science Information and Computing Sciences] 4

Background

▶ Personal project of Mozilla employee ▶ Sponsored by Mozilla Research ▶ First stable release (1.0) in 2015 ▶ Used in Firefox and by Dropbox ▶ Most loved programming language - SO Developer Survey

slide-5
SLIDE 5

[Faculty of Science Information and Computing Sciences] 5

Quick Overview

▶ Statically typed ▶ Functional and Imperative paradigms ▶ Strict language

slide-6
SLIDE 6

[Faculty of Science Information and Computing Sciences] 6

Beautiful Quotes

Mozilla Research: “Rust is a systems programming language that runs blazingly fast, prevents segfaults, and guarantees thread safety.” “It fuses the expressive and intuitive syntax of high-level languages with the control and performance of a low-level language.”

slide-7
SLIDE 7

[Faculty of Science Information and Computing Sciences] 7

Features

▶ Zero-cost abstractions ▶ Move semantics ▶ Guaranteed memory safety ▶ Threads without data races ▶ Trait-based generics ▶ Pattern matching ▶ Type inference ▶ Minimal runtime ▶ Efficient C bindings

slide-8
SLIDE 8

[Faculty of Science Information and Computing Sciences] 7

Features

▶ Zero-cost abstractions ▶ Move semantics ▶ Guaranteed memory safety ▶ Threads without data races ▶ Trait-based generics ▶ Pattern matching ▶ Type inference ▶ Minimal runtime ▶ Efficient C bindings

slide-9
SLIDE 9

[Faculty of Science Information and Computing Sciences] 7

Features

▶ Zero-cost abstractions ▶ Move semantics ▶ Guaranteed memory safety ▶ Threads without data races ▶ Trait-based generics ▶ Pattern matching ▶ Type inference ▶ Minimal runtime ▶ Efficient C bindings

slide-10
SLIDE 10

[Faculty of Science Information and Computing Sciences] 7

Features

▶ Zero-cost abstractions ▶ Move semantics ▶ Guaranteed memory safety ▶ Threads without data races ▶ Trait-based generics ▶ Pattern matching ▶ Type inference ▶ Minimal runtime ▶ Efficient C bindings

slide-11
SLIDE 11

[Faculty of Science Information and Computing Sciences] 7

Features

▶ Zero-cost abstractions ▶ Move semantics ▶ Guaranteed memory safety ▶ Threads without data races ▶ Trait-based generics ▶ Pattern matching ▶ Type inference ▶ Minimal runtime ▶ Efficient C bindings

slide-12
SLIDE 12

[Faculty of Science Information and Computing Sciences] 7

Features

▶ Zero-cost abstractions ▶ Move semantics ▶ Guaranteed memory safety ▶ Threads without data races ▶ Trait-based generics ▶ Pattern matching ▶ Type inference ▶ Minimal runtime ▶ Efficient C bindings

slide-13
SLIDE 13

[Faculty of Science Information and Computing Sciences] 7

Features

▶ Zero-cost abstractions ▶ Move semantics ▶ Guaranteed memory safety ▶ Threads without data races ▶ Trait-based generics ▶ Pattern matching ▶ Type inference ▶ Minimal runtime ▶ Efficient C bindings

slide-14
SLIDE 14

[Faculty of Science Information and Computing Sciences] 7

Features

▶ Zero-cost abstractions ▶ Move semantics ▶ Guaranteed memory safety ▶ Threads without data races ▶ Trait-based generics ▶ Pattern matching ▶ Type inference ▶ Minimal runtime ▶ Efficient C bindings

slide-15
SLIDE 15

[Faculty of Science Information and Computing Sciences] 7

Features

▶ Zero-cost abstractions ▶ Move semantics ▶ Guaranteed memory safety ▶ Threads without data races ▶ Trait-based generics ▶ Pattern matching ▶ Type inference ▶ Minimal runtime ▶ Efficient C bindings

slide-16
SLIDE 16

[Faculty of Science Information and Computing Sciences] 7

Features

▶ Zero-cost abstractions ▶ Move semantics ▶ Guaranteed memory safety ▶ Threads without data races ▶ Trait-based generics ▶ Pattern matching ▶ Type inference ▶ Minimal runtime ▶ Efficient C bindings

slide-17
SLIDE 17

[Faculty of Science Information and Computing Sciences] 8

Variable bindings

▶ Use let keyword to create binding ▶ Bindings are immutable by default ▶ Lhs not a name, but a pattern ▶ Type annotations

fn main() { let y = 3; } let (a, b) = (1, 2); let mut x : u8 = 10; // Make x mutable x = 255;

slide-18
SLIDE 18

[Faculty of Science Information and Computing Sciences] 9

Functions

▶ Use fn keyword ▶ Statements vs expressions

fn square(x: i32) -> i32 { x * x // Expression } fn printSomething() { println!("Something"); // Statement }

slide-19
SLIDE 19

[Faculty of Science Information and Computing Sciences] 10

Arrays and tuples

Arrays can be created like this:

let mut y = [4, 5, 6]; let second = y[1]; let mut z = [1; 10]; // Ten elements initialized to 1

Tuples are created as follows:

let mut tuple = (1, 2); let x = tuple.0; let y = tuple.1; println!("Value of y is {}", y); let (x, y, z) = (1, 2, 3); // Destructured tuple

slide-20
SLIDE 20

[Faculty of Science Information and Computing Sciences] 11

Control flow

▶ If, else, else if… ▶ Loops, like loop, while and for

let x = 2; let y = if x == 3 { 4 } else { 5 }; loop { println!("Infinite loop"); } for x in 1..10 {} for (index, value) in (1..10).enumerate() { } let a = [1, 2, 3, 4, 5]; for elem in a.iter() { println!("the value is: {}", elem); }

slide-21
SLIDE 21

[Faculty of Science Information and Computing Sciences] 12

Vectors

▶ Dynamic arrays ▶ Allocated on heap (as opposed to arrays)

let mut v = vec![1,2,3] for i in v {} // For loop takes ownership for i in &v {} // Reference for i in &mut v {} // Mutable reference

slide-22
SLIDE 22

[Faculty of Science Information and Computing Sciences] 13

Structs

▶ Comparable to classes. ▶ Can also have methods and associated functions

struct Point { x: i32, y: i32, } impl Point { fn print_xy(&self) { println!("x is {}, y is {}", self.x, self.y); } } let point = Point { x: 3, y: 6 }; point.print_xy(); // Shows x is 3, y is 6.

slide-23
SLIDE 23

[Faculty of Science Information and Computing Sciences] 14

Match

▶ Comparable to switch ▶ Allows matching on expressions

let x: u32 = 3; match x { 1 => println!("one"), 2 => println!("two"), _ => println!("three or more"), }

slide-24
SLIDE 24

[Faculty of Science Information and Computing Sciences] 15

Enums

▶ Define type and enumerate on its variants

enum Choice { Milk(i32), Tea(String), } let m = Choice::Milk(20);

slide-25
SLIDE 25

[Faculty of Science Information and Computing Sciences] 16

Generics

▶ Generic structs, enums and functions.

fn takes_anything<T, U>(x: T, u: U) {} struct Value<T> { value : T } enum Choice<T> { Milk(T), }

slide-26
SLIDE 26

[Faculty of Science Information and Computing Sciences] 17

Traits

▶ Somewhat comparable to an interface ▶ Use trait bounds on generics

struct Square { side: f64, } trait HasArea { fn area(&self) -> f64; } impl HasArea for Square { fn area(&self) -> f64 { self.side * self.side } } fn print_area<T: HasArea>(shape: T) { println!("This shape has an area of {}", shape.area()); }

slide-27
SLIDE 27

[Faculty of Science Information and Computing Sciences] 18

Much, much more..

▶ Smart pointers ▶ Concurrency ▶ Closures ▶ …

slide-28
SLIDE 28

[Faculty of Science Information and Computing Sciences] 19

Memory management

Different systems

▶ Garbage collection ▶ Automatic reference counting ▶ Ownership

Key difference: When are objects on the heap deallocated?

slide-29
SLIDE 29

[Faculty of Science Information and Computing Sciences] 19

Memory management

Different systems

▶ Garbage collection ▶ Automatic reference counting ▶ Ownership

Key difference: When are objects on the heap deallocated?

slide-30
SLIDE 30

[Faculty of Science Information and Computing Sciences] 19

Memory management

Different systems

▶ Garbage collection ▶ Automatic reference counting ▶ Ownership

Key difference: When are objects on the heap deallocated?

slide-31
SLIDE 31

[Faculty of Science Information and Computing Sciences] 19

Memory management

Different systems

▶ Garbage collection ▶ Automatic reference counting ▶ Ownership

Key difference: When are objects on the heap deallocated?

slide-32
SLIDE 32

[Faculty of Science Information and Computing Sciences] 20

Ownership

▶ Every value has one variable that is its owner.

Example

let x = String::from("hello");

The variable x is the owner of the string object “hello” on the heap. The string object will be deallocated when x goes out of scope.

slide-33
SLIDE 33

[Faculty of Science Information and Computing Sciences] 20

Ownership

▶ Every value has one variable that is its owner.

Example

let x = String::from("hello");

The variable x is the owner of the string object “hello” on the heap. The string object will be deallocated when x goes out of scope.

slide-34
SLIDE 34

[Faculty of Science Information and Computing Sciences] 21

Ownership

Another example

fn say_hello(name: String) { println!("Hello {}", name); } let x = String::from("Wouter"); say_hello(x); say_hello(x); // Error!

The ownership is passed into say_hello, which deallocates our string when its scope ends.

slide-35
SLIDE 35

[Faculty of Science Information and Computing Sciences] 21

Ownership

Another example

fn say_hello(name: String) { println!("Hello {}", name); } let x = String::from("Wouter"); say_hello(x); say_hello(x); // Error!

The ownership is passed into say_hello, which deallocates our string when its scope ends.

slide-36
SLIDE 36

[Faculty of Science Information and Computing Sciences] 22

Borrowing

▶ Pass a reference to the function ▶ Ownership is not transferred ▶ Immutable (by default)

fn say_hello(name: &String) { println!("Hello {}", name); } let x = String::from("Wouter"); say_hello(&x); say_hello(&x); // Works!

slide-37
SLIDE 37

[Faculty of Science Information and Computing Sciences] 23

Mutable references

fn double(value: &mut isize) { *value = *value * 2; } let mut x: isize = 3; double(&mut x); // x = 6

slide-38
SLIDE 38

[Faculty of Science Information and Computing Sciences] 24

Slices

▶ Taking a reference to part of a collection

let some_numbers = [0, 1, 2, 3, 4, 5]; let slice = &some_numbers[0..3]; // [0, 1, 2]

slide-39
SLIDE 39

[Faculty of Science Information and Computing Sciences] 25

Smart pointers

▶ Box ▶ Enables recursive data types

slide-40
SLIDE 40

[Faculty of Science Information and Computing Sciences] 26

Smart pointers

enum List { Cons(isize, Box<List>), Nil } let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Cons(3, Box::new(List::Nil)))))); // list = (1 : (2 : (3 : [])))

slide-41
SLIDE 41

[Faculty of Science Information and Computing Sciences] 27

Reference counting using smart pointers

▶ Sometimes you may want more freedom ▶ For these situations, reference counting is also possible in Rust

let a = Rc::new(String::from("Blue"));

slide-42
SLIDE 42

[Faculty of Science Information and Computing Sciences] 28

Reference counting using smart pointers

struct Node { value: isize, next: Vec<Rc<Node>> } let d = Rc::new(Node { value: 8, next: vec![] }); let b = Rc::new(Node { value: 3, next: vec![Rc::clone(&d)] }); let c = Rc::new(Node { value: 5, next: vec![Rc::clone(&d)] }); let a = Rc::new(Node { value: 2, next: vec![Rc::clone(&b), Rc::clone(&c)] });

slide-43
SLIDE 43

[Faculty of Science Information and Computing Sciences] 29

What problems does Rust (intend to) solve?

▶ Memory safety ▶ “Fearless” concurrency ▶ Performance

slide-44
SLIDE 44

[Faculty of Science Information and Computing Sciences] 30

Memory safety

Null pointers

▶ Easy to forget ▶ The Option enum (similar to Maybe in Haskell) ▶ The Result enum

slide-45
SLIDE 45

[Faculty of Science Information and Computing Sciences] 31

Memory safety

Null pointers

enum Option<T> { Some(T), None, } enum Result<T, E> { Ok(T), Err(E), }

slide-46
SLIDE 46

[Faculty of Science Information and Computing Sciences] 32

Memory safety

Dangling references

▶ No garbage collector! ▶ Borrowing rules/Lifetimes

slide-47
SLIDE 47

[Faculty of Science Information and Computing Sciences] 33

Memory safety

Buffer overruns

▶ Safety ▶ Index in array ▶ Compile/Runtime checks

slide-48
SLIDE 48

[Faculty of Science Information and Computing Sciences] 34

“Fearless” concurrency

Borrowing rules

▶ Only one owner ▶ No aliasing ▶ Easier debugging

slide-49
SLIDE 49

[Faculty of Science Information and Computing Sciences] 35

“Fearless” concurrency

Message passing

let (tx, rx) = mpsc::channel(); thread::spawn(move || { let val = 5; tx.send(val).unwrap(); }); let received = rx.recv().unwrap();

slide-50
SLIDE 50

[Faculty of Science Information and Computing Sciences] 36

“Fearless” concurrency

Shared state

let m = Mutex::new(0); thread::spawn(move || { let mut num = m.lock().unwrap(); *num = 5; });

slide-51
SLIDE 51

[Faculty of Science Information and Computing Sciences] 37

Performance

▶ No garbage collector ▶ Fewer run time checks

slide-52
SLIDE 52

[Faculty of Science Information and Computing Sciences] 38

Practical

▶ Mature & intuitive package manager (cargo) ▶ Lots of libraries from a vibrant community ▶ i.a. IDE priority this year ▶ Basic linting and debugging ▶ Get started on https://doc.rust-lang.org ▶ Used because of safety, performance and being practical

slide-53
SLIDE 53

[Faculty of Science Information and Computing Sciences] 39

Conclusion

“Rust is a systems programming language that runs blazingly fast, prevents segfaults, and guarantees thread safety.” “It fuses the expressive and intuitive syntax of high-level languages with the control and performance of a low-level language.”

slide-54
SLIDE 54

[Faculty of Science Information and Computing Sciences] 40

Questions