SlideShare a Scribd company logo
Nicholas Matsakis!
Mozilla Research
So, you want more control?
C++?
OMG!
2
Too slow!
Other things you might want:!
• Standalone library, as you would get from C
• Interface with another runtime, e.g. Ruby
  • Use a really cool language :)
My god, it’s full of bugs
3
Dangling pointers
!
Segmentation faults
!
Double frees
!
Uninitialized data
!
Null pointer exceptions
!
Resource leaks (DB handle)
!
Data races
Solved by GC
Not so much.
4
Systems programming without the hassle
crashes!
heisenbugs!
fear
Parallel!

Recommended for you

Introduction to Rust
Introduction to RustIntroduction to Rust
Introduction to Rust

This document provides an introduction to the Rust programming language. It describes that Rust was developed by Mozilla Research beginning in 2009 to combine the type safety of Haskell, concurrency of Erlang, and speed of C++. Rust reached version 1.0 in 2015 and is a generic, multiparadigm systems programming language that runs on platforms including ARM, Apple, Linux, Windows and embedded devices. It emphasizes security, performance and fine-grained memory safety without garbage collection.

introductionrust
Rust: Systems Programming for Everyone
Rust: Systems Programming for EveryoneRust: Systems Programming for Everyone
Rust: Systems Programming for Everyone

Video and slides synchronized, mp3 and slide download available at URL http://bit.ly/28XnVtb. Felix Klock describe the core concepts of the Rust language (ownership, borrowing, and lifetimes), as well as the tools beyond the compiler for open source software component distribution (cargo, crates.io). Filmed at qconlondon.com. Felix Klock is a research engineer at Mozilla, where he works on the Rust compiler, runtime libraries, and language design. He previously worked on the ActionScript Virtual Machine for the Adobe Flash runtime. Klock is one of the developers of the Larceny Scheme language runtime.

qconlondonfelix klockqcon
The Rust Programming Language: an Overview
The Rust Programming Language: an OverviewThe Rust Programming Language: an Overview
The Rust Programming Language: an Overview

Brief overview of the Rust system programming language. Provides a concise introduction of its basic features, with an emphasis on its memory safety features (ownership, moves, borrowing) and programming style with generic functions, structures, and traits.

rustprogramming languagesprogramming
// sums all the positive values in `v`
fn sum_pos(v: &Vec<i32>) -> i32 {
let mut sum = 0;
for i in v.iter().filter(|i| **i > 0) {
sum += *i;
}
sum
}
High-level coding
5
Iterators.
Closures.
Assembly code
6
leaq (%rdi,%rsi,4), %rcx
xorl %eax, %eax
jmp .LBB5_1
.LBB5_3:
addl %edx, %eax
.align 16, 0x90
.LBB5_1:
cmpq %rdi, %rcx
je .LBB5_4
movl (%rdi), %edx
addq $4, %rdi
testl %edx, %edx
jle .LBB5_1
jmp .LBB5_3
.LBB5_4:
retq
fn foo(v: &Vec<i32>) -> i32 {
v.iter()
.filter(|i| **i > 0)
.map(|i| *i)
.sum()
}
Higher-level coding
7
…generates the same assembly code.
Safe
8
fn this_wont_compile(v: &mut Vec<i32>) -> i32 {
let mut sum = 0;
for &i in v.iter() {
sum += i;
if i > 0 { v.push(0); }
}
sum
}
error: cannot borrow `*v` as mutable because it is also borrowed
as immutable
if i > 0 { v.push(0); }
^
note: previous borrow of `*v` occurs here; the immutable borrow
prevents subsequent moves or mutable borrows of `*v` until
the borrow ends
for &i in v.iter() {
^
Might free
underlying buffer.

Recommended for you

Rust言語紹介
Rust言語紹介Rust言語紹介
Rust言語紹介

The document discusses Rust, a systems programming language developed by Mozilla. It provides an agenda, introduction to the speaker and company, why Rust was chosen, basic Rust concepts, and examples of Rust code. Memory safety is emphasized as Rust avoids vulnerabilities like memory leaks and use-after-free by using a borrow checker to validate references. Examples demonstrate immutable and mutable references, structs, functions, and memory management using Box to move values.

rust
Why rust?
Why rust?Why rust?
Why rust?

This document discusses why Rust is a useful programming language. It provides an introduction to Rust, highlighting its memory safety features, ownership and borrowing system, and functional programming aspects like iterators and closures. Examples are given to demonstrate how Rust prevents common bugs like dangling pointers and iterator invalidation. The talk also covers Rust's type system, enums, patterns matching, and its Cargo package manager.

rustintroductionc++
Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017 Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017

Rust provides memory safety without garbage collection through its ownership and borrowing model that is checked at compile time. Ownership rules ensure that references to resources like vectors remain valid by moving the vector when it is passed to a function. Borrowing allows immutable or mutable references to a resource, but not both at the same time, avoiding data races. Rust achieves performance comparable to C++ through its zero-cost abstractions and moves semantics that avoid unnecessary data copying.

programmingrust language
Parallel
9
use std::thread;
fn qsort(data: &mut [i32])
if data.len() <= 1 {
return;
}
let mid = partition(data[0], data);
let (left, right) = data.split_at_mut(mid);
let t1 = thread::scoped(|| qsort(left));
qsort(right);
}
Sort left and right
in parallel.Caveat: unstable API.
Open and welcoming
Rust has been open source from the beginning.
!
Open governance model based on public RFCs.
!
We have an active, amazing community.
❤
10
Getting Started
11
You can either install Rust, or
just use play.rust-lang.org
Exercises are available at:
!
http://nikomatsakis.github.io/rust-tutorial-boston-20150722/
Outline
12
1. The big ideas:!
a. Ownership
b. Borrowing
2. Everyday life:!
a. Data types
b. Modules and privacy
c. Cargo

Recommended for you

Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовRust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов

Последние 15 лет между разработчиками на Java и на C++ ведётся спор о том, какой язык программирования хуже — Java или C++. Программы на C++ глючат, падают, и в них утекает память. Программы на Java тормозят и требуют слишком много памяти. Rust — новый язык программирования, разрабатываемый компанией Mozilla — решает проблемы Java и C++: программы, написанные на Rust, одновременно быстрые и безопасные. Rust является таким же низкоуровневым, close-to-metal языком программирования, как и C++, однако в язык встроены конструкции, позволяющие на этапе компиляции доказывать, что в программе не случится обращения к неинициализированной памяти (механизм borrowed pointers). Большая часть моего рассказа будет посвящена описанию этого механизма.

Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...

A talk on how the JVM's JIT works, how to monitor it, and how to interpret the results for great justice.

jvmbytecodeperformance
Rust Intro @ Roma Rust meetup
Rust Intro @ Roma Rust meetup Rust Intro @ Roma Rust meetup
Rust Intro @ Roma Rust meetup

A 30' introduction to Rust, presented at the Rome Rust meetup on May 10, 2017. A visual explanation of ownership, borrowing, and lifetime.

embeddedmozillalanguage
Ownership!
!
n. The act, state, or right of possessing something.
13
Borrow!
!
v. To receive something with the promise of returning it.
The Big Idea
Ownership and borrowing:!
!
1. All memory has a clear owner.
2. Others can borrow from the owner.
3. Owner cannot free or mutate the
memory while it is borrowed.
14
Ownership/Borrowing
Memory
safety
Data-race
freedom
No need for
a runtime
GCC++
15
Clean up the mess
16
http://mylifeandkids.com/messy-house-edition-boys-bedroom-2/

Recommended for you

Down the Rabbit Hole
Down the Rabbit HoleDown the Rabbit Hole
Down the Rabbit Hole

The document discusses exploring interesting Java features and how they are compiled and executed by the Java Virtual Machine (JVM). It begins with an introduction and overview of the topics that will be covered, including looking at Java bytecode, compiler logs, and generated native code. Examples of simple "Hello World" and math programs are provided and their compilation steps are examined at the bytecode, logging and native code levels to demonstrate how Java code is handled by the JVM.

jvmbytecodejava
Как мы охотимся на гонки (data races) или «найди багу до того, как она нашла ...
Как мы охотимся на гонки (data races) или «найди багу до того, как она нашла ...Как мы охотимся на гонки (data races) или «найди багу до того, как она нашла ...
Как мы охотимся на гонки (data races) или «найди багу до того, как она нашла ...

При создании высоконагруженных систем, как серверных, так и клиентских, становится всё сложнее обходиться без многопоточности. Однако программирование многопоточных приложений не становится легче – во многом из-за проблемы гонок (data races).Гонки практически не поддаются «отлову» при помощи классических методов тестирования, так как не проявляются при каждом запуске программы. Рассказ пойдёт об инструменте поиска гонок «ThreadSanitizer», который был разработан и внедрен в Google. ThreadSanitizer позволяет находить гонки в программах, написанных на C, C++, Java и работающих на Linux, Mac Os и Windows. Мы поделимся опытом реального использования этого инструмента при тестировании крупных проектов, таких как Google Chrome или серверное ПО Google. Вы узнаете, какие гонки мы находили, с какими сложностями сталкивались при обучении пользователей, как внедряли регулярное автоматическое тестирование.

google
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++

Rust — это современный, практический, быстрый и безопасный язык программирования. Некоторые говорят, что Rust — это как C++, если бы его писал человек, знающий Haskell. Система типов Rust решает главную проблему C++ — небезопасность. C++ очень легко сделать ошибки, которые приведут к поломкам (например, use after free). Rust позволяет писать безопасный код, сохраняя при этом выразительность и околонулевые накладные расходы C++. В докладе будут подробно описаны механизмы языка, которые контролируют безопасность программы. Хотя в данный момент Rust ещё не подходит для использования в продакшне, его всё равно стоит изучать. Во-первых, потому что это очень интересный подход к программированию, а во-вторых, потому что через несколько лет для разработки требовательных к ресурсам программ будет необходим именно Rust или другой похожий инструмент.

c++
Ownership
17
fn give() {
let mut vec = vec![];
vec.push(1);
vec.push(2);
take(vec);
…
}
fn take(vec: Vec<i32>) {
// …
}
!
!
!
Ownership
Take ownership
of a Vec<i32>
18
fn give() {
let mut vec = Vec::new();
vec.push(1);
vec.push(2);
take(vec);
…
}
vec.push(2);
Compiler enforces moves
fn take(vec: Vec<i32>) {
// …
}
!
!
!Error: vec has been moved
Prevents:
- use after free
- double moves
- …
19
void give() {
Vector vec = …;
vec.add(1);
vec.add(2);
take(vec);
vec.add(3);
}
void take(Vector vec) {
// …
}
!
!
!
“Ownership” in Java
Take reference
to Vector
20

Recommended for you

Python Asíncrono - Async Python
Python Asíncrono - Async PythonPython Asíncrono - Async Python
Python Asíncrono - Async Python

Presentación de la charla impartida en el meetup de Python Madrid sobre Asincronía en Python https://www.meetup.com/es-ES/python-madrid/events/268111847/

pythonasyncconcurrent
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done right

Multithreading with modern C++ is hard. Undefined variables, Deadlocks, Livelocks, Race Conditions, Spurious Wakeups, the Double Checked Locking Pattern, etc. And at the base is the new Memory-Modell which make the life not easier. The story of things which can go wrong is very long. In this talk I give you a tour through the things which can go wrong and show how you can avoid them.

c++cpprussia
Clojure ♥ cassandra
Clojure ♥ cassandra Clojure ♥ cassandra
Clojure ♥ cassandra

This talk will explore two libraries, a Cassandra native CQL client and a Clojure DSL for writing CQL3 queries. This will demonstrate how Cassandra and Clojure are a great fit, show the strength of the functional approach to this domain and how in particular the data centric nature of Clojure makes a lot of sense in this context.

clojurecqlcassandra
Mutability
21
fn prefix_sum(mut v: Vec<i32>) -> Vec<i32> {
let mut sum = 0;
for i in 0 .. v.len() {
sum += v[i];
v[i] = sum;
}
v
}
http://is.gd/wCtQQZ
1, 2, 3, 4 1, 3, 6, 10
(caller) (prefix sum)
Clone
22
fn main() {
let d = vec![1, 3, 4, 10];
let ps = prefix_sum(d);
println!("prefix sum of {:?} is {:?}",
d, ps);
}
http://is.gd/nbuxdV
Clone
23
fn main() {
let d = vec![1, 3, 4, 10];
let ps = prefix_sum(d.clone());
println!("prefix sum of {:?} is {:?}",
d, ps);
}
http://is.gd/nbuxdV
1, 2, 3, 4 1, 3, 6, 10
(caller) (prefix sum)
1, 2, 3, 4
24
struct Point {
x: u32,
y: u32
}
!
fn area(ul: Point, lr: Point) -> u32 {
(lr.x - ul.x) * (lr.y - ul.y)
}
!
fn main() {
let origin = Point { x: 0, y: 0 };
let unit = Point { x: 1, y: 1 };
let here = Point { x: 5, y: 6 };
println!(“{:?}”, area(origin, unit));
println!(“{:?}”, area(origin, here));
}
Declare a struct
type Point with two
fields, x and y.
// 1
// ?
http://is.gd/5dDnaH
32-bit unsigned integer

Recommended for you

Introduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System LanguageIntroduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System Language

Rust is a multi-paradigm systems programming language focused on safety, especially safe concurrency. Rust is syntactically similar to C++, but is designed to provide better memory safety while maintaining high performance. This talk covers the following: principles of design, features, and applications. There are many successful projects used Rust, including browsers, operation systems, and database management systems, which will be also discussed in the talk.

rustsystemprogramming
To Swift 2...and Beyond!
To Swift 2...and Beyond!To Swift 2...and Beyond!
To Swift 2...and Beyond!

A three-part presentation on the Swift programming language: • An introduction to Swift for Objective-C developers • Changes in Swift 2 • What's coming in Swift 2.2 & 3.0

objective-cdevelopmentllvm
Rust vs C++
Rust vs C++Rust vs C++
Rust vs C++

Rust and C++ are both systems programming languages but Rust provides better memory safety while maintaining performance. Rust uses a borrow checker to catch errors at compile time and disallows null references, while C++ relies more on programmer discipline. Rust also guarantees thread safety by preventing data races through its ownership and borrowing model.

c++rustc++ corehard spring 2018
“Copy” types
25
#[derive(Copy, Clone)]
struct Point {
x: u32,
y: u32
}
26
Default: Type cannot be copied.
Values move from place to place.
Example: File descriptor.
!
Clone: Type is expensive to copy,
so make it explicit by calling clone().
Example: Vector, hashtable.!
!
Copy: Type is implicitly copied
whenever it is referenced.
Example: u32, i32, Point
27
Exercise #1.
* Actually: mutation only in controlled circumstances
*
Shared borrow (&T)
Sharing Mutation

Recommended for you

Rust: Reach Further
Rust: Reach FurtherRust: Reach Further
Rust: Reach Further

Presentation on Rust given at Multicore Day 2017 (RISE SICS). https://www.sics.se/events/multicore-day-2017

rust
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible Java

For years we’ve been told that the JVM’s amazing optimizers can take your running code and make it “fast” or “as fast as C++” or “as fast as C”…or sometimes “faster than C”. And yet we don’t often see this happen in practice, due in large part to (good and bad) development patterns that have taken hold in the Java world. In this talk, we’ll explore the main reasons why Java code rarely runs as fast as C or C++ and how you can write really bad Java code that the JVM will do a better job of optimizing. We’ll take some popular microbenchmarks and burn them to the ground, monitoring JIT logs and assembly dumps along the way.

assemblyjvmjit
PyParis 2017 / Camisole : A secure online sandbox to grade student - Antoine ...
PyParis 2017 / Camisole : A secure online sandbox to grade student - Antoine ...PyParis 2017 / Camisole : A secure online sandbox to grade student - Antoine ...
PyParis 2017 / Camisole : A secure online sandbox to grade student - Antoine ...

Camisole is a secure online sandbox for grading student code submissions. It uses Linux namespaces and cgroups to isolate untrusted code and enforce resource limits like memory and time. Camisole has a simple HTTP API and supports many programming languages through a modular language definition system. It aims to securely evaluate code submissions for online courses and programming contests in a lightweight and language-agnostic way.

datapythoneducation
Mutable borrow (&mut T)
29
Sharing Mutation
30
fn sum(v: Vec<i32>) -> i32 {
let mut s = 0;
for i in 0 .. v.len() {
s += v[i];
}
s
}
!
fn main() {
let v = vec![1, 2, 3];
println!(“{:?}”, sum(v));
}
Take ownership
of a Vec<i32>
Give ownership
31
fn sum(v: &Vec<i32>) -> i32 {
let mut s = 0;
for i in 0 .. v.len() {
s += v[i];
}
s
}
!
fn main() {
let v = vec![1, 2, 3];
println!(“{:?}”, sum(&v));
}
Borrow!
Vec<i32>
Lend the vector
http://is.gd/aHalet
32
fn prefix_sum(v: &mut Vec<i32>) {
let mut s = 0;
for i in 0 .. v.len() {
s += v[i];
v[i] = s;
}
}
!
fn main() {
let mut v = vec![1, 2, 3];
prefix_sum(&mut v);
println!("{:?}", v);
}
Mutable borrow
Mutable loan
http://is.gd/jvKmF2

Recommended for you

Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]

The document provides an overview of the C programming language. It begins by explaining that Objective-C extends standard ANSI C with object-oriented capabilities. It then discusses why C remains important today due to its use in libraries, operating systems, and as the base for many other popular languages. The document proceeds to cover basic C concepts like variables, data types, functions, flow control, pointers, memory allocation, and I/O parameters. It emphasizes that C provides high performance with a minimal footprint while abstracting away the CPU and memory.

codemashcsdk
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go

Go 1.10 Release Party, featuring what's new in Go 1.10 and a few deep dives into how Go works. Presented at the PDX Go Meetup on April 24th, 2018. https://www.meetup.com/PDX-Go/events/248938586/

gogolangprogramming
Pydiomatic
PydiomaticPydiomatic
Pydiomatic

The document discusses properties in Python classes. Properties allow accessing attributes through normal attribute syntax, while allowing custom behavior through getter and setter methods. This avoids directly accessing attributes and allows for validation in setters. Properties are defined using the @property and @setter decorators, providing a cleaner syntax than regular getter/setter methods. They behave like regular attributes but allow underlying method calls.

 
by rik0
object-oriented programmingitertoolsfirst order functions
fn example() {
let mut names = Vec::new();
names.push(..);
names.push(..);
let name = &names[1];
names.push(..);
print(name);
}
names
data
length
capacity
“brson”
“pcwalton”
name
“brson”
“pcwalton”
“acrichto”
Sharing: more than
one pointer to same
memory.
Dangling pointer: pointer
to freed memory.
Mutating the vector
freed old contents.
33
Rust solution
34
Compile-time read-write-lock:!
!
Creating a shared reference to X “read locks” X.
- Other readers OK.
- No writers.
- Lock lasts until reference goes out of scope.
!
Creating a mutable reference to X “writes locks” X.
- No other readers or writers.
- Lock lasts until reference goes out of scope.
Never have a reader/writer at same time.
fn example() {
let mut names = Vec::new();
names.push(“brson”);
names.push(“pcwalton”);
let name = &names[1];
names.push(“acrichto”);
println!(“{:?}”, name);
}
Borrow “locks”
`names` until `name`
goes out of scopeError: cannot mutate
`names` while borrowed
35
http://is.gd/jeKW1E
Outside of borrow scope — OK.
Scope of borrow
in this case covers
only the loop body.
36
http://is.gd/thMY5N
fn main() {
let mut names = Vec::new();
names.push("brson");
names.push("pcwalton");
for i in 0 .. names.len() {
let name = &names[i];
names.push("acrichto");
println!("{:?}", name);
}
names.push("acrichto");
}

Recommended for you

Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico

This document summarizes key aspects of iteration in Python based on the provided document: 1. Python supports multiple ways of iteration including for loops and generators. For loops are preferred for iteration over finite collections while generators enable infinite iteration. 2. Common iteration patterns include iterating over elements, indices, or both using enumerate(). Numerical iteration can be done with for loops or while loops. 3. Functions are first-class objects in Python and can be passed as arguments or returned as values, enabling functional programming patterns like mapping and filtering.

itaday2scoprire python
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh

ES6 is Nigh is a presentation on the future of JavaScript. It discusses the history of JavaScript and why ES6 is important for advancing the language. The presentation outlines many new features being added in ES6, such as arrow functions, classes, modules, template strings, symbols, generators, and proxies. It emphasizes that ES6 is purely additive and introduces these features without breaking backwards compatibility.

javascript
C++ Boot Camp Part 2
C++ Boot Camp Part 2C++ Boot Camp Part 2
C++ Boot Camp Part 2

This document provides an overview of tools and concepts for using C++, including: - Compiling and linking code by splitting classes into header and source files. - Static vs dynamic libraries and how they are included in programs. - Setting up include and library paths to import the Box2D physics library into a C++ project. - Popular C++ libraries like Boost, GUI frameworks like Qt and SDL, and game engines like Unity and Unreal that can be used in C++ projects. - Tips for using debugging tools, documentation tools like Doxygen, and build systems like CMake in C++ development.

Rust reasons about scopes
37
fn main() {
let mut names = Vec::new();
names.push("brson");
names.push("pcwalton");
for i in 0 .. names.len() {
let name = &names[i];
println!("{:?}", name);
names.push("acrichto");
}
names.push("acrichto");
}
Even though reference is not used,
it is still in scope for the entire block..
http://is.gd/pLE8bb
Take a break.
38
Daily life in Rust
39
Methods
40
struct Point {
x: f32,
y: f32,
}
!
impl Point {
fn new() -> Point {
Point { x: 0.0, y: 0.0 }
}
!
fn negate(&self) -> Point {
Point { x: -self.x, y: -self.y }
}
} http://is.gd/KbbORT

Recommended for you

Klee and angr
Klee and angrKlee and angr
Klee and angr

Klee and Angr are tools for symbolic execution. Klee is a symbolic virtual machine that executes programs symbolically and generates test cases by solving constraints. It works on LLVM bitcode. Angr is a Python framework for analyzing binaries using static and dynamic symbolic analysis. It lifts binaries into an intermediate representation called VEX to analyze machine code across architectures. Both tools explore all paths in a program and solve path constraints to generate inputs that execute each path.

kleeangrsymbolic execution
Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and Prosper

Spock is a testing framework written in Groovy that allows developers to write tests in a business readable domain specific language. It combines the benefits of specification-based testing and mock-based testing. Some key features of Spock include the ability to write feature methods with given, when, and then blocks; use fixtures for setup and cleanup; parameterize tests with data tables in where blocks; make assertions about interactions with mock objects; and write tests in a BDD style with descriptive language. Spock's tests are themselves a good source of documentation on how to write and use Spock tests.

unit testingspockgroovy
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code

Just how different is "Modern C++" from "legacy C++"? Is my codebase ready for C++17? Do I need a full rewrite of my app to modernize my code? If you're looking for answers to some of these questions, join us for a session on how to effectively leverage modern C++17 features in your existing C++ projects; and no, you don't need to rewrite your app.

Common derivations
41
#[derive(PartialEq)]
+ #[derive(PartialOrd)]
#[derive(Clone)]
#[derive(Debug)]
x == y, x != y
x < y, x <= y, …
x.clone()
+ #[derive(Copy)] use(x); use(x);
println!(“{:?}”, x);
#[derive(Hash)] HashMap<T>
Enums
42
struct Point {..}
!
enum Shape {
Circle { origin: Point,
radius: f32 },
!
Rectangle { ul: Point,
lr: Point }
}
43
struct Point {..}
!
enum Shape {
Circle { origin: Point, radius: f32 },
Rectangle { ul: Point, lr: Point }
}
!
impl Shape {
fn unit_circle() -> Shape {
Shape::Circle {
origin: Point { x: 0.0, y: 0.0 },
radius: 1.0
}
}
}
const PI: f32 = 3.14159;
impl Shape {
fn area(&self) -> f32 {
match *self {
Shape::Circle { origin: _, radius: r } =>
PI * r * r,
!
Shape::Rectangle { ul, lr } =>
(lr.y - ul.y).abs() * (lr.x - ul.x).abs()
}
}
}
44
http://is.gd/a2YcvG

Recommended for you

How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code

Just how different is "Modern C++" from "legacy C++"? Is my codebase ready for C++17? Do I need a full rewrite of my app to modernize my code? If you're looking for answers to some of these questions, join us for a session on how to effectively leverage modern C++17 features in your existing C++ projects; and no, you don't need to rewrite your app.

c++visual studio
Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)

Slides from the Ruby Topic Maps Tutorial I gave at TMRA in October 2007. New upload for new RTM website: http://rtm.topicmapslab.de

topicmapsrubyrtmtmratopicmapsruby
Power Leveling your TypeScript
Power Leveling your TypeScriptPower Leveling your TypeScript
Power Leveling your TypeScript

One Does Not… write TypeScript so easily! In this Meetup talk, I'll share the tricks and pain points I had to learn in my first 6 months of professional TypeScript. The goal is to spare the reader many hours of Stack Overflow...

Option
45
enum Option<T> {
None,
Some(T),
}
No null types
46
class Shape {
Color color;
!
Shape() { }
!
Color getColor(Color default) {
if (color != null)
return color;
return default;
}
}
(Java)
47
struct Shape {
color: Option<Color>
}
!
impl Shape {
fn new() -> Shape {
Shape { color: None }
}
!
fn get_color(&self, default: Color) -> Color {
match self.color {
None => default,
Some(ref c) => c.clone()
}
}
} (Rust)
48
match self.color {
None => default,
Some(ref c) => c.clone()
}
if let Some(ref c) = self.color {
c.clone()
} else {
default
}
self.color.unwrap_or(default)
self.color.unwrap_or_else(|| default)

Recommended for you

What the &~#@&lt;!? (Pointers in Rust)
What the &~#@&lt;!? (Pointers in Rust)What the &~#@&lt;!? (Pointers in Rust)
What the &~#@&lt;!? (Pointers in Rust)

University of Virginia cs4414: Operating Systems http://rust-class.org Explicit vs. Automatic Memory Management Garbage Collection, Reference Counting Rust ownership types For embedded notes, see: http://rust-class.org/class9-pointers-in-rust.html

pointersownershipreference counting
Python in 30 minutes!
Python in 30 minutes!Python in 30 minutes!
Python in 30 minutes!

This document provides an introduction to the Python programming language over 30 minutes. It covers basic Python concepts like variables, data types, conditionals, loops, functions, imports, strings, lists, tuples, sets, dictionaries, and classes. Code examples are provided to demonstrate how to use these features. The document encourages learners to continue learning Python through online documentation and resources.

pythonprogrammingintroduction
Learn Python 3 for absolute beginners
Learn Python 3 for absolute beginnersLearn Python 3 for absolute beginners
Learn Python 3 for absolute beginners

This document provides an introduction to the Python programming language over 30 slides. It covers key Python concepts like variables, data types, conditionals, loops, functions, imports, strings, lists, tuples, sets, dictionaries, classes and input/output. Examples are given for each concept to demonstrate how it works in Python. The document concludes by encouraging the reader to continue learning Python through online documentation and resources.

pythonprogrammingpython for beginers
Slices
49
fn main() {
// Heap-allocated.
let v: Vec<i32> = vec![1, 2, 3, 4];
!
// Reference to one element.
let e: &i32 = &v[1];
!
// Reference to many elements.
let slice: &[i32] = &v[1..3];
}
http://is.gd/QftPT8
Mutable slices
50
fn main() {
// Heap-allocated.
let mut v: Vec<i32> = vec![1, 2, 3, 4];
println!(“v={:?}”, v);
{
let slice = &mut v[..];
slice[1] += 22;
}
println!(“v={:?}”, v);
}
http://is.gd/31rKv5
For loops and slices
51
for x in &v {
// x is an &i32
}
let v: Vec<i32> = vec![1, 2, 3, 4];
for x in &mut v {
// x is an &mut i32
}
for x in v {
// x is an i32
} // v is consumed after loop
for converts its argument into an iterator
using the IntoIterator trait
Iterators
52
struct PlayerScore {
player_name: String,
score: u32
}
!
fn high_scorers(v: Vec<PlayerScore>)
-> Vec<(String, u32)>
{
v.into_iter()
.filter(|ps| ps.score > 20)
.map(|ps| (ps.player_name, ps.score))
.collect()
}

Recommended for you

Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm

Kotlin is a JVM language developed by Jetbrains. Its version 1.0 (production ready) was released at the beginning of the year and made some buzz within the android community. This session proposes to discover this language, which takes up some aspects of groovy or scala, and that is very close to swift in syntax and concepts. We will see how Kotlin boosts the productivity of Java & Android application development and how well it accompanies reactive development.

androidlanguagespring
Folding Cheat Sheet #7 - seventh in a series
Folding Cheat Sheet #7 - seventh in a seriesFolding Cheat Sheet #7 - seventh in a series
Folding Cheat Sheet #7 - seventh in a series

The three duality theorems of fold.

duality theorems of foldduality theoremsfold
Software development... for all? (keynote at ICSOFT'2024)
Software development... for all? (keynote at ICSOFT'2024)Software development... for all? (keynote at ICSOFT'2024)
Software development... for all? (keynote at ICSOFT'2024)

Our world runs on software. It governs all major aspects of our life. It is an enabler for research and innovation, and is critical for business competitivity. Traditional software engineering techniques have achieved high effectiveness, but still may fall short on delivering software at the accelerated pace and with the increasing quality that future scenarios will require. To attack this issue, some software paradigms raise the automation of software development via higher levels of abstraction through domain-specific languages (e.g., in model-driven engineering) and empowering non-professional developers with the possibility to build their own software (e.g., in low-code development approaches). In a software-demanding world, this is an attractive possibility, and perhaps -- paraphrasing Andy Warhol -- "in the future, everyone will be a developer for 15 minutes". However, to make this possible, methods are required to tweak languages to their context of use (crucial given the diversity of backgrounds and purposes), and the assistance to developers throughout the development process (especially critical for non-professionals). In this keynote talk at ICSOFT'2024 I presented enabling techniques for this vision, supporting the creation of families of domain-specific languages, their adaptation to the usage context; and the augmentation of low-code environments with assistants and recommender systems to guide developers (professional or not) in the development process.

softwaremodel-driven engineeringdomain-specific languages
Programming in the large
53
Cargo
54
> cargo new my_project
> cargo new —-bin my_project
> cd my_project
> emacs
Create a template for a new project:
Edit your project:
> cargo build [—-release]
> cargo test
Build and test your project:
http://doc.crates.io/guide.html
Dependencies
55
[package]
name = "hello_world"
version = "0.1.0"
authors = ["Your Name <you@example.com>”]
!
[dependencies]
regex = "0.1.41"
Cargo.toml
lib.rs
extern crate regex;
Modules
56
mod data;
mod code;
lib.rs/main.rs
data/mod.rs
mod point;
mod shape;
data/point.rs
struct Point {
}
::
data
point
shape
code
data/shape/mod.rs
struct Point {
}

Recommended for you

WEBINAR SLIDES: CCX for Cloud Service Providers
WEBINAR SLIDES: CCX for Cloud Service ProvidersWEBINAR SLIDES: CCX for Cloud Service Providers
WEBINAR SLIDES: CCX for Cloud Service Providers

Browse the slides from our recent webinar hosted by Divine Odazie, our tech evangelist.

cloudccxcloud services
A Comparative Analysis of Functional and Non-Functional Testing.pdf
A Comparative Analysis of Functional and Non-Functional Testing.pdfA Comparative Analysis of Functional and Non-Functional Testing.pdf
A Comparative Analysis of Functional and Non-Functional Testing.pdf

A robust software testing strategy encompassing functional and non-functional testing is fundamental for development teams. These twin pillars are essential for ensuring the success of your applications. But why are they so critical? Functional testing rigorously examines the application's processes against predefined requirements, ensuring they align seamlessly. Conversely, non-functional testing evaluates performance and reliability under load, enhancing the end-user experience.

non functional testingfunctional testing
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptxWired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptx

In this talk, we will explore strategies to optimize the success rate of storing and retaining new information. We will discuss scientifically proven ideal learning intervals and content structures. Additionally, we will examine how to create an environment that improves our focus while you remain in the “flow”. Lastly we will also address the influence of AI on learning capabilities. In the dynamic field of software development, this knowledge will empower you to accelerate your learning curve and support others in their learning journeys.

Often used to make
a mod test for unit tests,
or for demonstations.
Inline modules
57
mod data {
mod point {
..
}
!
mod shape {
..
}
}
!
mod code {
lib.rs/main.rs Exactly the same as
creating a separate file.
Use
58
::
data
point
shape
code
code.rs
use data::point::Point;
data/mod.rs
use data::point::Point;
use self::point::Point;
data/shape.rs
use data::point::Point;
use super::point::Point;
Privacy
59
Privacy is the default, use pub to override.
pub struct Point {
pub x: f32,
pub y: f32,
}
impl Point {
pub fn m(&self);
}
pub enum Shape {
…
}
pub mod child;
Private means: code in this module or a descendant.
Where to learn more
60
doc.rust-lang.org/book
users.rust-lang.org / IRC / Stackoverflow
doc.rust-lang.org/std

Recommended for you

MVP Mobile Application - Codearrest.pptx
MVP Mobile Application - Codearrest.pptxMVP Mobile Application - Codearrest.pptx
MVP Mobile Application - Codearrest.pptx

An MVP (Minimum Viable Product) mobile application is a streamlined version of a mobile app that includes only the core features necessary to address the primary needs of its users. The purpose of an MVP is to validate the app concept with minimal resources, gather user feedback, and identify any areas for improvement before investing in a full-scale development. This approach allows businesses to quickly launch their app, test its market viability, and make data-driven decisions for future enhancements, ensuring a higher likelihood of success and user satisfaction.

mvp developmentmvp software developmentmvp mobile application
Responsibilities of Fleet Managers and How TrackoBit Can Assist.pdf
Responsibilities of Fleet Managers and How TrackoBit Can Assist.pdfResponsibilities of Fleet Managers and How TrackoBit Can Assist.pdf
Responsibilities of Fleet Managers and How TrackoBit Can Assist.pdf

What do fleet managers do? What are their duties, responsibilities, and challenges? And what makes a fleet manager effective and successful? This blog answers all these questions.

fleet managersresponsibilities of fleet mana
ENISA Threat Landscape 2023 documentation
ENISA Threat Landscape 2023 documentationENISA Threat Landscape 2023 documentation
ENISA Threat Landscape 2023 documentation

ENISA Threat Landscape 2023

61
Thanks for listening!

More Related Content

What's hot

Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02
nikomatsakis
 
Rust: Unlocking Systems Programming
Rust: Unlocking Systems ProgrammingRust: Unlocking Systems Programming
Rust: Unlocking Systems Programming
C4Media
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...
Claudio Capobianco
 
Introduction to Rust
Introduction to RustIntroduction to Rust
Introduction to Rust
Jean Carlo Machado
 
Rust: Systems Programming for Everyone
Rust: Systems Programming for EveryoneRust: Systems Programming for Everyone
Rust: Systems Programming for Everyone
C4Media
 
The Rust Programming Language: an Overview
The Rust Programming Language: an OverviewThe Rust Programming Language: an Overview
The Rust Programming Language: an Overview
Roberto Casadei
 
Rust言語紹介
Rust言語紹介Rust言語紹介
Rust言語紹介
Paweł Rusin
 
Why rust?
Why rust?Why rust?
Why rust?
Mats Kindahl
 
Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017 Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017
pramode_ce
 
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовRust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Yandex
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Charles Nutter
 
Rust Intro @ Roma Rust meetup
Rust Intro @ Roma Rust meetup Rust Intro @ Roma Rust meetup
Rust Intro @ Roma Rust meetup
Claudio Capobianco
 
Down the Rabbit Hole
Down the Rabbit HoleDown the Rabbit Hole
Down the Rabbit Hole
Charles Nutter
 
Как мы охотимся на гонки (data races) или «найди багу до того, как она нашла ...
Как мы охотимся на гонки (data races) или «найди багу до того, как она нашла ...Как мы охотимся на гонки (data races) или «найди багу до того, как она нашла ...
Как мы охотимся на гонки (data races) или «найди багу до того, как она нашла ...
yaevents
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++
Yandex
 
Python Asíncrono - Async Python
Python Asíncrono - Async PythonPython Asíncrono - Async Python
Python Asíncrono - Async Python
Javier Abadía
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done right
Platonov Sergey
 
Clojure ♥ cassandra
Clojure ♥ cassandra Clojure ♥ cassandra
Clojure ♥ cassandra
Max Penet
 
Introduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System LanguageIntroduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System Language
安齊 劉
 
To Swift 2...and Beyond!
To Swift 2...and Beyond!To Swift 2...and Beyond!
To Swift 2...and Beyond!
Scott Gardner
 

What's hot (20)

Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02
 
Rust: Unlocking Systems Programming
Rust: Unlocking Systems ProgrammingRust: Unlocking Systems Programming
Rust: Unlocking Systems Programming
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...
 
Introduction to Rust
Introduction to RustIntroduction to Rust
Introduction to Rust
 
Rust: Systems Programming for Everyone
Rust: Systems Programming for EveryoneRust: Systems Programming for Everyone
Rust: Systems Programming for Everyone
 
The Rust Programming Language: an Overview
The Rust Programming Language: an OverviewThe Rust Programming Language: an Overview
The Rust Programming Language: an Overview
 
Rust言語紹介
Rust言語紹介Rust言語紹介
Rust言語紹介
 
Why rust?
Why rust?Why rust?
Why rust?
 
Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017 Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017
 
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовRust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
 
Rust Intro @ Roma Rust meetup
Rust Intro @ Roma Rust meetup Rust Intro @ Roma Rust meetup
Rust Intro @ Roma Rust meetup
 
Down the Rabbit Hole
Down the Rabbit HoleDown the Rabbit Hole
Down the Rabbit Hole
 
Как мы охотимся на гонки (data races) или «найди багу до того, как она нашла ...
Как мы охотимся на гонки (data races) или «найди багу до того, как она нашла ...Как мы охотимся на гонки (data races) или «найди багу до того, как она нашла ...
Как мы охотимся на гонки (data races) или «найди багу до того, как она нашла ...
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++
 
Python Asíncrono - Async Python
Python Asíncrono - Async PythonPython Asíncrono - Async Python
Python Asíncrono - Async Python
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done right
 
Clojure ♥ cassandra
Clojure ♥ cassandra Clojure ♥ cassandra
Clojure ♥ cassandra
 
Introduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System LanguageIntroduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System Language
 
To Swift 2...and Beyond!
To Swift 2...and Beyond!To Swift 2...and Beyond!
To Swift 2...and Beyond!
 

Similar to Rust tutorial from Boston Meetup 2015-07-22

Rust vs C++
Rust vs C++Rust vs C++
Rust vs C++
corehard_by
 
Rust: Reach Further
Rust: Reach FurtherRust: Reach Further
Rust: Reach Further
nikomatsakis
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible Java
Charles Nutter
 
PyParis 2017 / Camisole : A secure online sandbox to grade student - Antoine ...
PyParis 2017 / Camisole : A secure online sandbox to grade student - Antoine ...PyParis 2017 / Camisole : A secure online sandbox to grade student - Antoine ...
PyParis 2017 / Camisole : A secure online sandbox to grade student - Antoine ...
Pôle Systematic Paris-Region
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Chris Adamson
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
Rodolfo Carvalho
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
rik0
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
PyCon Italia
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
Domenic Denicola
 
C++ Boot Camp Part 2
C++ Boot Camp Part 2C++ Boot Camp Part 2
C++ Boot Camp Part 2
Jesse Talavera-Greenberg
 
Klee and angr
Klee and angrKlee and angr
Klee and angr
Wei-Bo Chen
 
Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and Prosper
Ken Kousen
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
Microsoft Tech Community
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
Microsoft Tech Community
 
Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)
Benjamin Bock
 
Power Leveling your TypeScript
Power Leveling your TypeScriptPower Leveling your TypeScript
Power Leveling your TypeScript
Offirmo
 
What the &~#@&lt;!? (Pointers in Rust)
What the &~#@&lt;!? (Pointers in Rust)What the &~#@&lt;!? (Pointers in Rust)
What the &~#@&lt;!? (Pointers in Rust)
David Evans
 
Python in 30 minutes!
Python in 30 minutes!Python in 30 minutes!
Python in 30 minutes!
Fariz Darari
 
Learn Python 3 for absolute beginners
Learn Python 3 for absolute beginnersLearn Python 3 for absolute beginners
Learn Python 3 for absolute beginners
KingsleyAmankwa
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
Arnaud Giuliani
 

Similar to Rust tutorial from Boston Meetup 2015-07-22 (20)

Rust vs C++
Rust vs C++Rust vs C++
Rust vs C++
 
Rust: Reach Further
Rust: Reach FurtherRust: Reach Further
Rust: Reach Further
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible Java
 
PyParis 2017 / Camisole : A secure online sandbox to grade student - Antoine ...
PyParis 2017 / Camisole : A secure online sandbox to grade student - Antoine ...PyParis 2017 / Camisole : A secure online sandbox to grade student - Antoine ...
PyParis 2017 / Camisole : A secure online sandbox to grade student - Antoine ...
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
 
C++ Boot Camp Part 2
C++ Boot Camp Part 2C++ Boot Camp Part 2
C++ Boot Camp Part 2
 
Klee and angr
Klee and angrKlee and angr
Klee and angr
 
Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and Prosper
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
 
Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)
 
Power Leveling your TypeScript
Power Leveling your TypeScriptPower Leveling your TypeScript
Power Leveling your TypeScript
 
What the &~#@&lt;!? (Pointers in Rust)
What the &~#@&lt;!? (Pointers in Rust)What the &~#@&lt;!? (Pointers in Rust)
What the &~#@&lt;!? (Pointers in Rust)
 
Python in 30 minutes!
Python in 30 minutes!Python in 30 minutes!
Python in 30 minutes!
 
Learn Python 3 for absolute beginners
Learn Python 3 for absolute beginnersLearn Python 3 for absolute beginners
Learn Python 3 for absolute beginners
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
 

Recently uploaded

Folding Cheat Sheet #7 - seventh in a series
Folding Cheat Sheet #7 - seventh in a seriesFolding Cheat Sheet #7 - seventh in a series
Folding Cheat Sheet #7 - seventh in a series
Philip Schwarz
 
Software development... for all? (keynote at ICSOFT'2024)
Software development... for all? (keynote at ICSOFT'2024)Software development... for all? (keynote at ICSOFT'2024)
Software development... for all? (keynote at ICSOFT'2024)
miso_uam
 
WEBINAR SLIDES: CCX for Cloud Service Providers
WEBINAR SLIDES: CCX for Cloud Service ProvidersWEBINAR SLIDES: CCX for Cloud Service Providers
WEBINAR SLIDES: CCX for Cloud Service Providers
Severalnines
 
A Comparative Analysis of Functional and Non-Functional Testing.pdf
A Comparative Analysis of Functional and Non-Functional Testing.pdfA Comparative Analysis of Functional and Non-Functional Testing.pdf
A Comparative Analysis of Functional and Non-Functional Testing.pdf
kalichargn70th171
 
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptxWired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
SimonedeGijt
 
MVP Mobile Application - Codearrest.pptx
MVP Mobile Application - Codearrest.pptxMVP Mobile Application - Codearrest.pptx
MVP Mobile Application - Codearrest.pptx
Mitchell Marsh
 
Responsibilities of Fleet Managers and How TrackoBit Can Assist.pdf
Responsibilities of Fleet Managers and How TrackoBit Can Assist.pdfResponsibilities of Fleet Managers and How TrackoBit Can Assist.pdf
Responsibilities of Fleet Managers and How TrackoBit Can Assist.pdf
Trackobit
 
ENISA Threat Landscape 2023 documentation
ENISA Threat Landscape 2023 documentationENISA Threat Landscape 2023 documentation
ENISA Threat Landscape 2023 documentation
sofiafernandezon
 
ANSYS Mechanical APDL Introductory Tutorials.pdf
ANSYS Mechanical APDL Introductory Tutorials.pdfANSYS Mechanical APDL Introductory Tutorials.pdf
ANSYS Mechanical APDL Introductory Tutorials.pdf
sachin chaurasia
 
WhatsApp Tracker - Tracking WhatsApp to Boost Online Safety.pdf
WhatsApp Tracker -  Tracking WhatsApp to Boost Online Safety.pdfWhatsApp Tracker -  Tracking WhatsApp to Boost Online Safety.pdf
WhatsApp Tracker - Tracking WhatsApp to Boost Online Safety.pdf
onemonitarsoftware
 
FAST Channels: Explosive Growth Forecast 2024-2027 (Buckle Up!)
FAST Channels: Explosive Growth Forecast 2024-2027 (Buckle Up!)FAST Channels: Explosive Growth Forecast 2024-2027 (Buckle Up!)
FAST Channels: Explosive Growth Forecast 2024-2027 (Buckle Up!)
Roshan Dwivedi
 
Break data silos with real-time connectivity using Confluent Cloud Connectors
Break data silos with real-time connectivity using Confluent Cloud ConnectorsBreak data silos with real-time connectivity using Confluent Cloud Connectors
Break data silos with real-time connectivity using Confluent Cloud Connectors
confluent
 
Attendance Tracking From Paper To Digital
Attendance Tracking From Paper To DigitalAttendance Tracking From Paper To Digital
Attendance Tracking From Paper To Digital
Task Tracker
 
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
ThousandEyes
 
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTIONBITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
ssuser2b426d1
 
Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...
Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...
Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
active-directory-auditing-solution (2).pptx
active-directory-auditing-solution (2).pptxactive-directory-auditing-solution (2).pptx
active-directory-auditing-solution (2).pptx
sudsdeep
 
Prada Group Reports Strong Growth in First Quarter …
Prada Group Reports Strong Growth in First Quarter …Prada Group Reports Strong Growth in First Quarter …
Prada Group Reports Strong Growth in First Quarter …
908dutch
 
Safe Work Permit Management Software for Hot Work Permits
Safe Work Permit Management Software for Hot Work PermitsSafe Work Permit Management Software for Hot Work Permits
Safe Work Permit Management Software for Hot Work Permits
sheqnetworkmarketing
 
Overview of ERP - Mechlin Technologies.pptx
Overview of ERP - Mechlin Technologies.pptxOverview of ERP - Mechlin Technologies.pptx
Overview of ERP - Mechlin Technologies.pptx
Mitchell Marsh
 

Recently uploaded (20)

Folding Cheat Sheet #7 - seventh in a series
Folding Cheat Sheet #7 - seventh in a seriesFolding Cheat Sheet #7 - seventh in a series
Folding Cheat Sheet #7 - seventh in a series
 
Software development... for all? (keynote at ICSOFT'2024)
Software development... for all? (keynote at ICSOFT'2024)Software development... for all? (keynote at ICSOFT'2024)
Software development... for all? (keynote at ICSOFT'2024)
 
WEBINAR SLIDES: CCX for Cloud Service Providers
WEBINAR SLIDES: CCX for Cloud Service ProvidersWEBINAR SLIDES: CCX for Cloud Service Providers
WEBINAR SLIDES: CCX for Cloud Service Providers
 
A Comparative Analysis of Functional and Non-Functional Testing.pdf
A Comparative Analysis of Functional and Non-Functional Testing.pdfA Comparative Analysis of Functional and Non-Functional Testing.pdf
A Comparative Analysis of Functional and Non-Functional Testing.pdf
 
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptxWired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
 
MVP Mobile Application - Codearrest.pptx
MVP Mobile Application - Codearrest.pptxMVP Mobile Application - Codearrest.pptx
MVP Mobile Application - Codearrest.pptx
 
Responsibilities of Fleet Managers and How TrackoBit Can Assist.pdf
Responsibilities of Fleet Managers and How TrackoBit Can Assist.pdfResponsibilities of Fleet Managers and How TrackoBit Can Assist.pdf
Responsibilities of Fleet Managers and How TrackoBit Can Assist.pdf
 
ENISA Threat Landscape 2023 documentation
ENISA Threat Landscape 2023 documentationENISA Threat Landscape 2023 documentation
ENISA Threat Landscape 2023 documentation
 
ANSYS Mechanical APDL Introductory Tutorials.pdf
ANSYS Mechanical APDL Introductory Tutorials.pdfANSYS Mechanical APDL Introductory Tutorials.pdf
ANSYS Mechanical APDL Introductory Tutorials.pdf
 
WhatsApp Tracker - Tracking WhatsApp to Boost Online Safety.pdf
WhatsApp Tracker -  Tracking WhatsApp to Boost Online Safety.pdfWhatsApp Tracker -  Tracking WhatsApp to Boost Online Safety.pdf
WhatsApp Tracker - Tracking WhatsApp to Boost Online Safety.pdf
 
FAST Channels: Explosive Growth Forecast 2024-2027 (Buckle Up!)
FAST Channels: Explosive Growth Forecast 2024-2027 (Buckle Up!)FAST Channels: Explosive Growth Forecast 2024-2027 (Buckle Up!)
FAST Channels: Explosive Growth Forecast 2024-2027 (Buckle Up!)
 
Break data silos with real-time connectivity using Confluent Cloud Connectors
Break data silos with real-time connectivity using Confluent Cloud ConnectorsBreak data silos with real-time connectivity using Confluent Cloud Connectors
Break data silos with real-time connectivity using Confluent Cloud Connectors
 
Attendance Tracking From Paper To Digital
Attendance Tracking From Paper To DigitalAttendance Tracking From Paper To Digital
Attendance Tracking From Paper To Digital
 
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
 
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTIONBITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
 
Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...
Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...
Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...
 
active-directory-auditing-solution (2).pptx
active-directory-auditing-solution (2).pptxactive-directory-auditing-solution (2).pptx
active-directory-auditing-solution (2).pptx
 
Prada Group Reports Strong Growth in First Quarter …
Prada Group Reports Strong Growth in First Quarter …Prada Group Reports Strong Growth in First Quarter …
Prada Group Reports Strong Growth in First Quarter …
 
Safe Work Permit Management Software for Hot Work Permits
Safe Work Permit Management Software for Hot Work PermitsSafe Work Permit Management Software for Hot Work Permits
Safe Work Permit Management Software for Hot Work Permits
 
Overview of ERP - Mechlin Technologies.pptx
Overview of ERP - Mechlin Technologies.pptxOverview of ERP - Mechlin Technologies.pptx
Overview of ERP - Mechlin Technologies.pptx
 

Rust tutorial from Boston Meetup 2015-07-22

  • 2. So, you want more control? C++? OMG! 2 Too slow! Other things you might want:! • Standalone library, as you would get from C • Interface with another runtime, e.g. Ruby   • Use a really cool language :)
  • 3. My god, it’s full of bugs 3 Dangling pointers ! Segmentation faults ! Double frees ! Uninitialized data ! Null pointer exceptions ! Resource leaks (DB handle) ! Data races Solved by GC Not so much.
  • 4. 4 Systems programming without the hassle crashes! heisenbugs! fear Parallel!
  • 5. // sums all the positive values in `v` fn sum_pos(v: &Vec<i32>) -> i32 { let mut sum = 0; for i in v.iter().filter(|i| **i > 0) { sum += *i; } sum } High-level coding 5 Iterators. Closures.
  • 6. Assembly code 6 leaq (%rdi,%rsi,4), %rcx xorl %eax, %eax jmp .LBB5_1 .LBB5_3: addl %edx, %eax .align 16, 0x90 .LBB5_1: cmpq %rdi, %rcx je .LBB5_4 movl (%rdi), %edx addq $4, %rdi testl %edx, %edx jle .LBB5_1 jmp .LBB5_3 .LBB5_4: retq
  • 7. fn foo(v: &Vec<i32>) -> i32 { v.iter() .filter(|i| **i > 0) .map(|i| *i) .sum() } Higher-level coding 7 …generates the same assembly code.
  • 8. Safe 8 fn this_wont_compile(v: &mut Vec<i32>) -> i32 { let mut sum = 0; for &i in v.iter() { sum += i; if i > 0 { v.push(0); } } sum } error: cannot borrow `*v` as mutable because it is also borrowed as immutable if i > 0 { v.push(0); } ^ note: previous borrow of `*v` occurs here; the immutable borrow prevents subsequent moves or mutable borrows of `*v` until the borrow ends for &i in v.iter() { ^ Might free underlying buffer.
  • 9. Parallel 9 use std::thread; fn qsort(data: &mut [i32]) if data.len() <= 1 { return; } let mid = partition(data[0], data); let (left, right) = data.split_at_mut(mid); let t1 = thread::scoped(|| qsort(left)); qsort(right); } Sort left and right in parallel.Caveat: unstable API.
  • 10. Open and welcoming Rust has been open source from the beginning. ! Open governance model based on public RFCs. ! We have an active, amazing community. ❤ 10
  • 11. Getting Started 11 You can either install Rust, or just use play.rust-lang.org Exercises are available at: ! http://nikomatsakis.github.io/rust-tutorial-boston-20150722/
  • 12. Outline 12 1. The big ideas:! a. Ownership b. Borrowing 2. Everyday life:! a. Data types b. Modules and privacy c. Cargo
  • 13. Ownership! ! n. The act, state, or right of possessing something. 13 Borrow! ! v. To receive something with the promise of returning it.
  • 14. The Big Idea Ownership and borrowing:! ! 1. All memory has a clear owner. 2. Others can borrow from the owner. 3. Owner cannot free or mutate the memory while it is borrowed. 14
  • 16. Clean up the mess 16 http://mylifeandkids.com/messy-house-edition-boys-bedroom-2/
  • 18. fn give() { let mut vec = vec![]; vec.push(1); vec.push(2); take(vec); … } fn take(vec: Vec<i32>) { // … } ! ! ! Ownership Take ownership of a Vec<i32> 18
  • 19. fn give() { let mut vec = Vec::new(); vec.push(1); vec.push(2); take(vec); … } vec.push(2); Compiler enforces moves fn take(vec: Vec<i32>) { // … } ! ! !Error: vec has been moved Prevents: - use after free - double moves - … 19
  • 20. void give() { Vector vec = …; vec.add(1); vec.add(2); take(vec); vec.add(3); } void take(Vector vec) { // … } ! ! ! “Ownership” in Java Take reference to Vector 20
  • 21. Mutability 21 fn prefix_sum(mut v: Vec<i32>) -> Vec<i32> { let mut sum = 0; for i in 0 .. v.len() { sum += v[i]; v[i] = sum; } v } http://is.gd/wCtQQZ 1, 2, 3, 4 1, 3, 6, 10 (caller) (prefix sum)
  • 22. Clone 22 fn main() { let d = vec![1, 3, 4, 10]; let ps = prefix_sum(d); println!("prefix sum of {:?} is {:?}", d, ps); } http://is.gd/nbuxdV
  • 23. Clone 23 fn main() { let d = vec![1, 3, 4, 10]; let ps = prefix_sum(d.clone()); println!("prefix sum of {:?} is {:?}", d, ps); } http://is.gd/nbuxdV 1, 2, 3, 4 1, 3, 6, 10 (caller) (prefix sum) 1, 2, 3, 4
  • 24. 24 struct Point { x: u32, y: u32 } ! fn area(ul: Point, lr: Point) -> u32 { (lr.x - ul.x) * (lr.y - ul.y) } ! fn main() { let origin = Point { x: 0, y: 0 }; let unit = Point { x: 1, y: 1 }; let here = Point { x: 5, y: 6 }; println!(“{:?}”, area(origin, unit)); println!(“{:?}”, area(origin, here)); } Declare a struct type Point with two fields, x and y. // 1 // ? http://is.gd/5dDnaH 32-bit unsigned integer
  • 26. 26 Default: Type cannot be copied. Values move from place to place. Example: File descriptor. ! Clone: Type is expensive to copy, so make it explicit by calling clone(). Example: Vector, hashtable.! ! Copy: Type is implicitly copied whenever it is referenced. Example: u32, i32, Point
  • 28. * Actually: mutation only in controlled circumstances * Shared borrow (&T) Sharing Mutation
  • 29. Mutable borrow (&mut T) 29 Sharing Mutation
  • 30. 30 fn sum(v: Vec<i32>) -> i32 { let mut s = 0; for i in 0 .. v.len() { s += v[i]; } s } ! fn main() { let v = vec![1, 2, 3]; println!(“{:?}”, sum(v)); } Take ownership of a Vec<i32> Give ownership
  • 31. 31 fn sum(v: &Vec<i32>) -> i32 { let mut s = 0; for i in 0 .. v.len() { s += v[i]; } s } ! fn main() { let v = vec![1, 2, 3]; println!(“{:?}”, sum(&v)); } Borrow! Vec<i32> Lend the vector http://is.gd/aHalet
  • 32. 32 fn prefix_sum(v: &mut Vec<i32>) { let mut s = 0; for i in 0 .. v.len() { s += v[i]; v[i] = s; } } ! fn main() { let mut v = vec![1, 2, 3]; prefix_sum(&mut v); println!("{:?}", v); } Mutable borrow Mutable loan http://is.gd/jvKmF2
  • 33. fn example() { let mut names = Vec::new(); names.push(..); names.push(..); let name = &names[1]; names.push(..); print(name); } names data length capacity “brson” “pcwalton” name “brson” “pcwalton” “acrichto” Sharing: more than one pointer to same memory. Dangling pointer: pointer to freed memory. Mutating the vector freed old contents. 33
  • 34. Rust solution 34 Compile-time read-write-lock:! ! Creating a shared reference to X “read locks” X. - Other readers OK. - No writers. - Lock lasts until reference goes out of scope. ! Creating a mutable reference to X “writes locks” X. - No other readers or writers. - Lock lasts until reference goes out of scope. Never have a reader/writer at same time.
  • 35. fn example() { let mut names = Vec::new(); names.push(“brson”); names.push(“pcwalton”); let name = &names[1]; names.push(“acrichto”); println!(“{:?}”, name); } Borrow “locks” `names` until `name` goes out of scopeError: cannot mutate `names` while borrowed 35 http://is.gd/jeKW1E
  • 36. Outside of borrow scope — OK. Scope of borrow in this case covers only the loop body. 36 http://is.gd/thMY5N fn main() { let mut names = Vec::new(); names.push("brson"); names.push("pcwalton"); for i in 0 .. names.len() { let name = &names[i]; names.push("acrichto"); println!("{:?}", name); } names.push("acrichto"); }
  • 37. Rust reasons about scopes 37 fn main() { let mut names = Vec::new(); names.push("brson"); names.push("pcwalton"); for i in 0 .. names.len() { let name = &names[i]; println!("{:?}", name); names.push("acrichto"); } names.push("acrichto"); } Even though reference is not used, it is still in scope for the entire block.. http://is.gd/pLE8bb
  • 39. Daily life in Rust 39
  • 40. Methods 40 struct Point { x: f32, y: f32, } ! impl Point { fn new() -> Point { Point { x: 0.0, y: 0.0 } } ! fn negate(&self) -> Point { Point { x: -self.x, y: -self.y } } } http://is.gd/KbbORT
  • 41. Common derivations 41 #[derive(PartialEq)] + #[derive(PartialOrd)] #[derive(Clone)] #[derive(Debug)] x == y, x != y x < y, x <= y, … x.clone() + #[derive(Copy)] use(x); use(x); println!(“{:?}”, x); #[derive(Hash)] HashMap<T>
  • 42. Enums 42 struct Point {..} ! enum Shape { Circle { origin: Point, radius: f32 }, ! Rectangle { ul: Point, lr: Point } }
  • 43. 43 struct Point {..} ! enum Shape { Circle { origin: Point, radius: f32 }, Rectangle { ul: Point, lr: Point } } ! impl Shape { fn unit_circle() -> Shape { Shape::Circle { origin: Point { x: 0.0, y: 0.0 }, radius: 1.0 } } }
  • 44. const PI: f32 = 3.14159; impl Shape { fn area(&self) -> f32 { match *self { Shape::Circle { origin: _, radius: r } => PI * r * r, ! Shape::Rectangle { ul, lr } => (lr.y - ul.y).abs() * (lr.x - ul.x).abs() } } } 44 http://is.gd/a2YcvG
  • 46. No null types 46 class Shape { Color color; ! Shape() { } ! Color getColor(Color default) { if (color != null) return color; return default; } } (Java)
  • 47. 47 struct Shape { color: Option<Color> } ! impl Shape { fn new() -> Shape { Shape { color: None } } ! fn get_color(&self, default: Color) -> Color { match self.color { None => default, Some(ref c) => c.clone() } } } (Rust)
  • 48. 48 match self.color { None => default, Some(ref c) => c.clone() } if let Some(ref c) = self.color { c.clone() } else { default } self.color.unwrap_or(default) self.color.unwrap_or_else(|| default)
  • 49. Slices 49 fn main() { // Heap-allocated. let v: Vec<i32> = vec![1, 2, 3, 4]; ! // Reference to one element. let e: &i32 = &v[1]; ! // Reference to many elements. let slice: &[i32] = &v[1..3]; } http://is.gd/QftPT8
  • 50. Mutable slices 50 fn main() { // Heap-allocated. let mut v: Vec<i32> = vec![1, 2, 3, 4]; println!(“v={:?}”, v); { let slice = &mut v[..]; slice[1] += 22; } println!(“v={:?}”, v); } http://is.gd/31rKv5
  • 51. For loops and slices 51 for x in &v { // x is an &i32 } let v: Vec<i32> = vec![1, 2, 3, 4]; for x in &mut v { // x is an &mut i32 } for x in v { // x is an i32 } // v is consumed after loop for converts its argument into an iterator using the IntoIterator trait
  • 52. Iterators 52 struct PlayerScore { player_name: String, score: u32 } ! fn high_scorers(v: Vec<PlayerScore>) -> Vec<(String, u32)> { v.into_iter() .filter(|ps| ps.score > 20) .map(|ps| (ps.player_name, ps.score)) .collect() }
  • 53. Programming in the large 53
  • 54. Cargo 54 > cargo new my_project > cargo new —-bin my_project > cd my_project > emacs Create a template for a new project: Edit your project: > cargo build [—-release] > cargo test Build and test your project: http://doc.crates.io/guide.html
  • 55. Dependencies 55 [package] name = "hello_world" version = "0.1.0" authors = ["Your Name <you@example.com>”] ! [dependencies] regex = "0.1.41" Cargo.toml lib.rs extern crate regex;
  • 56. Modules 56 mod data; mod code; lib.rs/main.rs data/mod.rs mod point; mod shape; data/point.rs struct Point { } :: data point shape code data/shape/mod.rs struct Point { }
  • 57. Often used to make a mod test for unit tests, or for demonstations. Inline modules 57 mod data { mod point { .. } ! mod shape { .. } } ! mod code { lib.rs/main.rs Exactly the same as creating a separate file.
  • 58. Use 58 :: data point shape code code.rs use data::point::Point; data/mod.rs use data::point::Point; use self::point::Point; data/shape.rs use data::point::Point; use super::point::Point;
  • 59. Privacy 59 Privacy is the default, use pub to override. pub struct Point { pub x: f32, pub y: f32, } impl Point { pub fn m(&self); } pub enum Shape { … } pub mod child; Private means: code in this module or a descendant.
  • 60. Where to learn more 60 doc.rust-lang.org/book users.rust-lang.org / IRC / Stackoverflow doc.rust-lang.org/std