forked from hakimel/reveal.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2016_11_17_ownership_borrowing.html
666 lines (592 loc) · 26.6 KB
/
2016_11_17_ownership_borrowing.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Rust Introduction</title>
<meta name="author" content="Sascha Grunert">
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/theme/solarized.css">
<link rel="stylesheet" href="lib/css/zenburn.css">
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
</head>
<body>
<div class="reveal">
<div class="slides">
<section data-markdown>
<script type="text/template">
# Rust
## Ownership and Borrowing
<small>Second user group Meetup in Leipzig (2016-11-17)</small>
</script>
</section>
<section>
<section data-markdown>
<script type="text/template">
# Ownership
</script>
</section>
<section data-markdown>
<script type="text/template">
## Essentials for a safe language:
- You decide the lifetime of each value in your program
- Rust frees memory and other resources belonging to a value promptly
- Your program will never use a pointer to an object after it has been freed
- Rust restricts your program how to use pointers at compile time
</script>
</section>
<section data-markdown>
<script type="text/template">
## Ownership for variables
- Every value has a clear owner
- If the "owner" gets "dropped", the value is also gone
```rust
fn my_print() {
let mut vector = vec![1, 1, 1]; // allocated memory
for i in 1..10 {
let next = vector[i-1] + vector[i+1];
vector.push(next);
}
println!("{:?}", vector);
} // value dropped here
```
`Vector<T>` is mainly a fat pointer (pointer, capacity,
length) on the stack pointing to the data on the heap.
</script>
</section>
<section data-markdown>
<script type="text/template">
## Ownership for other types
- structs own their members
- tuples, arrays, vectors own their elements
- every value has a single owner
- single values may own other values
```rust
struct Person {
name: String,
age: u8,
}
let mut people = Vec::new();
people.push(
Person {
name: "Tom".to_string(),
age: 28,
}
);
people.push(
Person {
name: "Max".to_string(),
age: 33,
}
);
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## Ownership restrictions
The ownership system will result in "trees", not flexible "graphs".
- borrowing possible (via referenes, non owning pointers)
- multiple owners possible within certain data types (Arc, Rc)
- move values from one owner to another (rearrange the tree)
</script>
</section>
</section>
<section>
<section data-markdown>
<script type="text/template">
# Moves
</script>
</section>
<section data-markdown>
<script type="text/template">
## Basics
- most operations move a value instead of copying
- results in low memory and processing time
- old owners after move uninitialized
```rust
let v = vec!["a".to_string(), "b".to_string(), "c".to_string()];
let a = v;
let b = v; // error: use of moved value
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## Drop
```rust
let mut s = "Test".to_string();
s = "Example".to_string(); // value "Test" dropped here
```
```rust
let mut s = "Test".to_string();
let t = s;
s = "Example".to_string(); // nothing dropped here
```
<br>
Drop trait gives flexibility:
```rust
struct HasDrop;
impl Drop for HasDrop {
fn drop(&mut self) {
println!("Dropping!");
}
}
fn main() {
let _x = HasDrop;
} // "Dropping!"
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## Move example
```rust
struct Person {
name: String,
age: u8,
}
let mut people = Vec::new(); // moves ownership to "people"
people.push(
Person {
name: "Tom".to_string(), // moves ownership, returns a String
age: 28,
} // Structure takes ownership of the String and u8
);
people.push(
Person {
name: "Max".to_string(),
age: 33,
}
); // Vector takes ownership of the person and its owners
```
- machine code optimized to be stored "where it belongs"
- moves just copy three words (a fat pointer)
</script>
</section>
<section data-markdown>
<script type="text/template">
## Control flow
```rust
let x = vec![1, 2, 3];
if condition {
my_func(x); // okay, to move from x here
} else {
another_func(x); // okay to also move from x here
}
test_func(x); // bad: x is uninitialized here
```
```rust
let x = vec![1, 2, 3];
loop {
my_func(x); // error: x is uninitialized after the first iteration
// x = get_a_vector(); // Solution: get a fresh value
}
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## Indexed content
```rust
// Build a vector of the strings '1' to '5'
let mut v = Vec::new();
for i in 1..6 {
v.push(i.to_string());
}
let third = v[2]; // error: cannot move out of indexed content
let fifth = v.pop().unwrap(); // Works if unwrap(); succeeds
// Removes the 2nd element and return it,
// replacing it with the last element.
let third = v.swap_remove(2);
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## Copy Types
- certain types implement the Copy (marker) trait
- integer and floating-point numeric types
- char and bool types
- tuple or fixed-size array of Copy types is itself a Copy type
- self defined types can also be copy:
```rust
#[derive(Copy, Clone)]
struct Label { number: u32 }
// Works
```
```rust
#[derive(Copy, Clone)]
struct Label { name: String }
// Does not work since String does not implement Copy
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## Shared Ownership
- most values have unique owners in Rust
- Arc/Rc allows to live values as long as everybody is done using it (smart pointer)
- Arc: Atomic Refernce Count (can be shared safely between threads)
- Rc: Reference Count (faster, not thread safe)
```rust
use std::rc::Rc;
let s = Rc::new("Test".to_string());
// Just creates another pointer to the data in the heap:
let t = s.clone(); // increment reference count
let u = s.clone(); // increment reference count
```
Rust drops the String if the last instance is dropped
</script>
</section>
</section>
<section>
<section data-markdown>
<script type="text/template">
# Borrowing
</script>
</section>
<section data-markdown>
<script type="text/template">
## Basics
- "References" are non owning pointer types
- must never outlive their referents
- are never `NULL`
- Creating new references is called "Borrowing"
- two reference types available:
- _Shared Reference_ (Copy): multiple reader
```rust
&T // shared, like a pointer to const data
```
- _Mutable Reference_ (not Copy): single writer
```rust
&mut T // mutable, like a pointer
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## Consuming data
```rust
use std::collections::HashMap;
// Create a simple HashMap
let mut map :HashMap<String, u8> = HashMap::new();
map.insert("Foo".to_owned(), 5);
map.insert("Bar".to_owned(), 15);
// Iterate over the map
for (name, number) in map {
println!("{} {}", name, number);
}
// does not work any more
// the hashmap is already consumed
let foo = map.get("Foo");
// ^^^ Value used after move
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## Borrowing data
```rust
use std::collections::HashMap;
// Create a simple HashMap
let mut map :HashMap<String, u8> = HashMap::new();
map.insert("Foo".to_owned(), 5);
map.insert("Bar".to_owned(), 15);
// Iterate over the map
for (name, number) in &map {
println!("{} {}", name, number);
}
// Works now
let foo = map.get("Foo");
println!("{:?}", foo); // prints "Some(5)"
```
```rust
// Standard vector operations:
fn sort(&mut self); // Takes a mutable reference, call vector.sort();
fn get(&self, index: usize) -> Option<T>; // Takes just a reference
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## Implicit dereferencing
References are close to `C/C++` pointers:
```rust
let x = 10;
let y = &x;
assert!(*y == 10);
```
```rust
let mut y = 10;
let x = &mut y;
*x *= 10;
assert!(*x == 100);
```
Dot `.` operator follows references automatically:
```rust
let point = (100, 200);
let r = &point;
assert_eq!(r.0, 100); // no (*r).0 needed
```
```rust
struct Point { x: i32, y: i32 }
let p = Point { x: 100, y: 200 };
let r1 :&Point = &p;
let r2 :&&Point = &r1;
let r3 :&&&Point = &r2;
assert_eq!(r3.y, 200);
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## Fat references
Some references are fat pointers:
- references to Vec or slice of an array: `&[T]`
- references to String: `&str`
References to expressions are possible as well:
```rust
fn some_function() -> usize { 10usize }
let r = &some_function();
assert_eq!(r + &10, 20);
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## Scope of borrowing
```rust
let y;
{
let x = 1;
y = &x;
}
assert_eq!(*y, 1); // error: x does not live long enough
```
- Rust assigns a lifetime to every reference
- Lifetime will be checked at compilation
Rust tries to infer the correct lifetime for you.
</script>
</section>
</section>
<section>
<section data-markdown>
<script type="text/template">
# Lifetimes
</script>
</section>
<section data-markdown>
<script type="text/template">
## Basics
- start with a `'` (e.g. 'a or 'static)
- 'static is the largest possible lifetime (must be initialized)
<br>
Functions can take lifetime parameters to specify lifetimes:
```rust
fn f<'a>(p: &'a i32) { ... }
```
<br>
Example, does this work?
```rust
fn f(p: &'static i32) { ... }
let x = 10;
f(&x);
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## References in function arguments
```rust
// Usually Rust infers this
fn smallest<'a>(v: &'a [i32]) -> &'a i32 {
let mut s = &v[0];
for r in &v[1..] {
if *r < *s { s = r; }
}
s
}
```
```rust
let s;
{
let items = [5, 3, 2, 0, 1, 6, 9];
s = smallest(&items);
}
assert_eq!(*s, 0); // error: items does not live long enough
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## References in structures
- references in structures needs explicit lifetime parameters
```rust
struct Items<'a> {
count: &'a i32
}
```
```rust
let storage;
{
let x = 5;
storage = Items { count: &x };
}
assert_eq!(*storage.count, 5); // error: x does not live long enough
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## Distinct lifetimes #1
```rust
struct Point<'a> {
x: &'a i32,
y: &'a i32,
}
```
```rust
let x = 5;
let r;
{
let y = 10;
{
let point = Point { x: &x, y: &y };
r = point.x;
}
}
```
Will it work?
</script>
</section>
<section data-markdown>
<script type="text/template">
## Distinct lifetimes #2
The constraints are impossible to satisfy: no lifetime
is shorter than y's scope, but longer than r's.
Solution:
```rust
struct Point<'a, 'b> {
x: &'a i32,
y: &'b i32
}
```
```rust
let x = 5;
let r;
{
let y = 10;
{
let point = Point { x: &x, y: &y };
r = point.x;
}
}
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## Share or Mutate?
Shared references makes the variable read only:
```rust
let v = vec![1, 2, 3];
let r = &v;
let move = v; // moves
println!("{}", r[0]);
// error: cannot move out of `v` because it is borrowed
```
Solution:
```rust
let v = vec![1, 2, 3];
{
let r = &v;
println!("{}", r[0]); // Works now
}
let move = v;
```
This makes iterator invalidation impossible!
</script>
</section>
<section data-markdown>
<script type="text/template">
Remember the Ownership tree:
<br>
## Shared access is read only access
_Multiple readers are possible_
<br>
## Mutable access is exclusive
_No other usable path to this referent possible_
</script>
</section>
<section data-markdown>
<script type="text/template">
## Examples
```rust
let mut x = 10;
let r1 = &x;
let r2 = &x; // multiple shared borrows
x += 10; // error: x already borrowed
let m = &mut x; // error: cannot borrow `x` as mutable because it is
// also borrowed as immutable
```
```rust
let mut y = 20;
let m1 = &mut y;
let m2 = &mut y; // error: cannot borrow as mutable more than once
let z = y; // error: cannot use `y` because it was mutably borrowed
```
```rust
let mut w = (1, 2);
let r = &w;
let r0 = &r.0; // okay: re borrowing shared as shared
let m1 = &mut r.1; // error: can't re borrow shared as mutable
```
```rust
let mut v = (1, 2);
let m = &mut v;
let m0 = &mut m.0; // okay: re borrowing mutable from mutable
*m0 = 42;
let r1 = &m.1; // okay: re borrowing shared from mutable,
// and doesn't overlap with m0
v.1; // error: access through other paths still forbidden
```
</script>
</section>
</section>
<section data-markdown>
<script type="text/template">
# Thank you!
</script>
</section>
</div>
</div>
<script src="lib/js/head.min.js"></script>
<script src="js/reveal.js"></script>
<script>
// More info https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
backgroundTransition: 'zoom',
center: true,
controls: true,
history: true,
progress: true,
transition: 'zoom',
// More info https://github.com/hakimel/reveal.js#dependencies
dependencies: [
{ src: 'plugin/markdown/marked.js' },
{ src: 'plugin/markdown/markdown.js' },
{ src: 'plugin/notes/notes.js', async: true },
{ src: 'plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } },
{ src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }
]
});
</script>
</body>
</html>