-
Notifications
You must be signed in to change notification settings - Fork 2
/
curry-on2015.html
1890 lines (1811 loc) · 128 KB
/
curry-on2015.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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="pandoc">
<meta name="author" content="Felix Klock (@pnkfelix), Mozilla" />
<title>Rust: A Type System You Didn't Know You Wanted</title>
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="stylesheet" href="reveal.js/css/reveal.css"/>
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
div.sourceCode { overflow-x: auto; }
table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
margin: 0; padding: 0; vertical-align: baseline; border: none; }
table.sourceCode { width: 100%; line-height: 100%; }
td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
td.sourceCode { padding-left: 5px; }
code > span.kw { color: #007020; font-weight: bold; } /* Keyword */
code > span.dt { color: #902000; } /* DataType */
code > span.dv { color: #40a070; } /* DecVal */
code > span.bn { color: #40a070; } /* BaseN */
code > span.fl { color: #40a070; } /* Float */
code > span.ch { color: #4070a0; } /* Char */
code > span.st { color: #4070a0; } /* String */
code > span.co { color: #60a0b0; font-style: italic; } /* Comment */
code > span.ot { color: #007020; } /* Other */
code > span.al { color: #ff0000; font-weight: bold; } /* Alert */
code > span.fu { color: #06287e; } /* Function */
code > span.er { color: #ff0000; font-weight: bold; } /* Error */
code > span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
code > span.cn { color: #880000; } /* Constant */
code > span.sc { color: #4070a0; } /* SpecialChar */
code > span.vs { color: #4070a0; } /* VerbatimString */
code > span.ss { color: #bb6688; } /* SpecialString */
code > span.im { } /* Import */
code > span.va { color: #19177c; } /* Variable */
code > span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code > span.op { color: #666666; } /* Operator */
code > span.bu { } /* BuiltIn */
code > span.ex { } /* Extension */
code > span.pp { color: #bc7a00; } /* Preprocessor */
code > span.at { color: #7d9029; } /* Attribute */
code > span.do { color: #ba2121; font-style: italic; } /* Documentation */
code > span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code > span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code > span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
</style>
<link rel="stylesheet" href="reveal.js/css/theme/mozilla-sandstone.css" id="theme">
<link rel="stylesheet" href="slide-style.css"/>
<link rel="stylesheet" href="code-style.css"/>
<!-- If the query includes 'print-pdf', include the PDF print sheet -->
<script>
if( window.location.search.match( /print-pdf/gi ) ) {
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'reveal.js/css/print/pdf.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
}
</script>
<!--[if lt IE 9]>
<script src="reveal.js/lib/js/html5shiv.js"></script>
<![endif]-->
</head>
<body>
<div class="reveal">
<div class="slides">
<section>
<h1 class="title">Rust: A Type System You Didn't Know You Wanted</h1>
<h2 class="author">Felix Klock (<code>@pnkfelix</code>), Mozilla</h2>
<h3 class="date"><a href="http://is.gd/3oAeuH">http://is.gd/3oAeuH</a> (Space goes to next slide; Arrows navigate; Esc gives overview.)</h3>
</section>
<section><section id="rust-what-why-how" class="titleslide slide level1 center center_align"><h1>Rust: What? Why? (How?)</h1></section><section id="rust-what" class="slide level2 left_align">
<h1>Rust: What</h1>
<ul>
<li><p>New systems programming language</p>
<ul>
<li><p>fast; FFI interface; data layout control</p></li>
<li><p>compete (and interface with) with C/C++</p></li>
</ul></li>
</ul>
<div class="fragment">
<ul>
<li><p>Mix in the classic hits of PL</p>
<ul>
<li>user-defined iterators, RAII, objects with vtable method dispatch, generics / F-bounded polymorphism, algebraic data types, affine types, et cetera</li>
</ul></li>
</ul>
</div>
<div class="fragment">
<ul>
<li><p>Safety</p>
<ul>
<li><p>Memory-safe, data-race free</p></li>
<li><p><a href="http://blog.rust-lang.org/2015/04/10/Fearless-Concurrency.html">Fearless concurrency</a></p></li>
</ul></li>
</ul>
</div>
</section><section id="rust-where" class="slide level2 left_align center">
<h1>Rust: Where</h1>
<p>Language and API docs</p>
<ul>
<li><p>All linked from top of <a href="http://www.rust-lang.org/" class="uri">http://www.rust-lang.org/</a></p></li>
<li><p>Starting points</p>
<p>The Book: <a href="https://doc.rust-lang.org/stable/book/" class="uri">https://doc.rust-lang.org/stable/book/</a></p>
<p>Standard API: <a href="https://doc.rust-lang.org/stable/std/" class="uri">https://doc.rust-lang.org/stable/std/</a></p></li>
<li><p>Playpen: <a href="http://play.rust-lang.org/" class="uri">http://play.rust-lang.org/</a></p></li>
</ul>
</section><section id="playpen-encore" class="slide level2 center center_align">
<h1>Playpen (encore)</h1>
<h3 id="httpplay.rust-lang.org"><a href="http://play.rust-lang.org/" class="uri">http://play.rust-lang.org/</a></h3>
</section></section>
<section><section id="motivational-demos" class="titleslide slide level1 center"><h1>Motivational Demos</h1></section><section id="a-taste" class="slide level2">
<h1>A taste</h1>
<ul>
<li>Three fast <em>"amuse bouches"</em>
<ul>
<li>not the main course</li>
<li>(not even an appetizer)</li>
</ul></li>
</ul>
</section><section id="abstraction-without-overhead" class="slide level2" data-transition="fade-out">
<h1>Abstraction without overhead</h1>
<p>The below <a href="http://is.gd/weGnJ0">loop demo</a> compiles down to tight code:</p>
<!--
```rust
#[allow(dead_code)]
fn main1() {
let v1: Vec<i32> = (-100..10).collect();
let s1 = sum_pos(&v1);
let v2: Vec<i32> = (-100..1000).collect();
let s2 = sum_pos(&v2);
println!("v1.len: {} s1: {} v2.len: {} s2: {}", v1.len(), s1, v2.len(), s2);
}
#[allow(dead_code)]
#[inline(never)]
```
-->
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="co">// sums all the positive values in `v`</span>
<span class="kw">fn</span> sum_pos(v: &<span class="dt">Vec</span><<span class="dt">i32</span>>) -> <span class="dt">i32</span> {
<span class="kw">let</span> <span class="kw">mut</span> sum = <span class="dv">0</span>;
<span class="kw">for</span> i <span class="kw">in</span> v.iter().filter(|i| **i > <span class="dv">0</span>) {
sum += *i;
}
sum
}</code></pre></div>
<!-- https://play.rust-lang.org/?gist=23a69161dd4421e2925f -->
</section><section id="abstraction-without-overhead-1" class="slide level2" data-transition="fade">
<h1>Abstraction without overhead</h1>
<p>Generated x86_64 machine code for <code class="sourceCode rust"><span class="kw">fn</span> sum_pos</code>:</p>
<div class="sourceCode"><pre class="sourceCode nasm"><code class="sourceCode nasm"> leaq (<span class="ot">%rdi,%rsi,4), %rcx</span>
xorl <span class="ot">%eax, %eax</span>
<span class="kw">jmp</span> .LBB5_1
<span class="fu">.LBB5_3:</span>
addl <span class="ot">%edx, %eax</span>
.<span class="kw">align</span> <span class="dv">16</span><span class="bn">, 0x90</span>
<span class="fu">.LBB5_1:</span>
cmpq <span class="ot">%rdi, %rcx</span>
<span class="kw">je</span> .LBB5_4
movl (<span class="ot">%rdi), %edx</span>
addq<span class="bn"> $4, </span><span class="ot">%rdi</span>
testl <span class="ot">%edx, %edx</span>
<span class="kw">jle</span> .LBB5_1
<span class="kw">jmp</span> .LBB5_3
<span class="fu">.LBB5_4:</span>
retq</code></pre></div>
</section><section id="abstraction-without-overhead-2" class="slide level2" data-transition="fade-in slide-out">
<h1>Abstraction without overhead</h1>
<p>Or, if the first was not high-level enough:</p>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">fn</span> foo(v: &<span class="dt">Vec</span><<span class="dt">i32</span>>) -> <span class="dt">i32</span> {
v.iter().filter(|i| **i > <span class="dv">0</span>).map(|i| *i).sum()
}</code></pre></div>
<p>(This <a href="http://is.gd/RPVIjt">second loop demo</a> compiles down to the <em>same</em> tight code!)</p>
</section><section id="memory-safety" class="slide level2">
<h1>Memory safety</h1>
<p>Example: catches <a href="http://is.gd/ShihgA">iterator invalidation bugs</a> (aka <code>ConcurrentModificationException</code> - at compile-time)</p>
<div class="sourceCode"><pre class="sourceCode rust compile_error"><code class="sourceCode rust"><span class="kw">fn</span> this_wont_compile(v: &<span class="kw">mut</span> <span class="dt">Vec</span><<span class="dt">i32</span>>) -> <span class="dt">i32</span> {
<span class="kw">let</span> <span class="kw">mut</span> sum = <span class="dv">0</span>;
<span class="kw">for</span> &i <span class="kw">in</span> v.iter() {
sum += i;
<span class="kw">if</span> i > <span class="dv">0</span> { v.push(<span class="dv">0</span>); }
<span class="co">// ~~~~~~~~~ invalid! (might realloc</span>
<span class="co">// the backing storage for `v`)</span>
}
sum
}</code></pre></div>
<pre class="fragment"><code>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() {
^</code></pre>
</section><section id="slick-fearless-concurrency" class="slide level2">
<h1>Slick, Fearless Concurrency</h1>
<p>See also <a href="http://blog.rust-lang.org/2015/04/10/Fearless-Concurrency.html">Fearless Concurrency</a> blog post.</p>
<!--
```rust
fn seq_max(partial_data: &[u8]) -> u8 {
*partial_data.iter().max().unwrap()
}
```
-->
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">use</span> std::thread;
<span class="kw">fn</span> par_max(data: &[<span class="dt">u8</span>]) -> <span class="dt">u8</span> {
<span class="kw">if</span> data.len() <= <span class="dv">4</span> { <span class="kw">return</span> seq_max(data); }
<span class="kw">let</span> len_4 = data.len() / <span class="dv">4</span>; <span class="co">// DATA = [A .., B .., C .., D..]</span>
<span class="kw">let</span> (q1, rest) = data.split_at(len_4); <span class="co">// (A.. \ B..C..D..)</span>
<span class="kw">let</span> (q2, rest) = rest.split_at(len_4); <span class="co">// (B.. \ C..D..)</span>
<span class="kw">let</span> (q3, q4) = rest.split_at(len_4); <span class="co">// (C.. \ D..)</span>
<span class="kw">let</span> t1 = thread::scoped(|| seq_max(q1)); <span class="co">// fork A..</span>
<span class="kw">let</span> t2 = thread::scoped(|| seq_max(q2)); <span class="co">// fork B..</span>
<span class="kw">let</span> t3 = thread::scoped(|| seq_max(q3)); <span class="co">// fork C..</span>
<span class="kw">let</span> v4 = seq_max(q4); <span class="co">// compute D..</span>
<span class="kw">let</span> (v1, v2, v3) = (t1.join(), t2.join(), t3.join()); <span class="co">// join!</span>
<span class="kw">return</span> seq_max(&[v1, v2, v3, v4]);
}</code></pre></div>
<p>(caveat: <a href="http://is.gd/zOH5aL">above</a> is using unstable <code>thread::scoped</code> API)</p>
<!--
```rust
#[test]
fn hi() {
let mut v = vec![2, 1, 10, 9, 8, 7, 6, 5, 4, 3];
let m = par_max(&v);
assert_eq!(m, 10);
}
```
-->
</section></section>
<section><section id="rust-why" class="titleslide slide level1 center"><h1>Rust: Why?</h1></section><section id="rust-why-1" class="slide level2 left_align center">
<h1>Rust: Why?</h1>
<ul>
<li>Why is Mozilla investing in this?</li>
</ul>
<div class="fragment">
<ul>
<li><p>To compete</p>
<p>C/C++ impedes ability to compete in the browser market</p></li>
</ul>
</div>
<div class="fragment">
<ul>
<li><p>Fast experimentation (and deployment)</p>
<p>⇒ Competitive Advantage</p></li>
</ul>
</div>
</section><section id="servo" class="slide level2 center left_align">
<h1>Servo</h1>
<div class="fragment">
<p>browser implementation research platform</p>
</div>
<div class="fragment">
<p>written in Rust</p>
</div>
<div class="fragment">
<h3 id="experiments">Experiments</h3>
<ul>
<li><p>parallel paint</p></li>
<li><p>parallel layout</p></li>
<li><p>parallel css selector matching</p></li>
</ul>
</div>
</section><section id="rust-a-note-on-goals" class="slide level2">
<h1>Rust: A note on goals</h1>
<div class="fragment">
<p>What is "soundness"?</p>
</div>
<div class="fragment">
<p>Segfault is not okay</p>
</div>
<div class="fragment">
<p>But: "clean" shutdown (e.g. on internal error) <em>is</em> okay</p>
</div>
<div class="fragment">
<p>Rust has <code class="sourceCode rust"><span class="pp">panic!</span></code>, and atop it <code class="sourceCode rust"><span class="pp">assert!</span></code> etc</p>
<p>(A panic unwinds the stack, cleaning up resources)</p>
<h3 id="so">So</h3>
</div>
<p>Rust uses dynamic checks (and resorts to <code class="sourceCode rust"><span class="pp">panic!</span></code>) where appropriate</p>
<div class="fragment">
<h3 id="but">But</h3>
<p>Prefers static assurances <em>when feasible</em></p>
<p>(we are pragmatists)</p>
</div>
</section></section>
<section><section id="rust-how" class="titleslide slide level1 center_align center"><h1>Rust: How?</h1></section><section id="rust-how-the-big-ideas" class="slide level2 center_align center">
<h1>Rust: How? (The Big Ideas)</h1>
<h3 id="ownership-move-semantics">Ownership + Move Semantics</h3>
<div class="fragment">
<p>(explicit resource control)</p>
</div>
<h3 id="borrowing">Borrowing</h3>
<div class="fragment">
<p>(brings back reference semantics)</p>
</div>
<h3 id="lifetimes">Lifetimes</h3>
<div class="fragment">
<p>(encode safety constraints between references)</p>
</div>
</section><section id="move-semantics" class="slide level2">
<h1><a href="http://is.gd/IZyTXN">Move Semantics</a></h1>
<p>Create (and modify) owned:</p>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="at">#[</span>test<span class="at">]</span>
<span class="kw">pub</span> <span class="kw">fn</span> create_owned() {
<span class="kw">let</span> <span class="kw">mut</span> vec = <span class="dt">Vec</span>::new(); <span class="co">// + (`vec` created ...</span>
vec.push(<span class="dv">2000</span>); <span class="co">// | ... and</span>
vec.push( <span class="dv">400</span>); <span class="co">// | also</span>
vec.push( <span class="dv">60</span>); <span class="co">// | mutated ...</span>
<span class="pp">println!</span>(<span class="st">"vec: {:?}"</span>, vec); <span class="co">// |</span>
<span class="kw">let</span> the_sum = sum(vec); <span class="co">// o ... and moved)</span>
<span class="co">// (starting here, access to `vec` is static error)</span>
<span class="pp">println!</span>(<span class="st">"the_sum: {}"</span>, the_sum);
}</code></pre></div>
<p>At scope end, clean up initialized (+ unmoved) variables</p>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">fn</span> sum(v: <span class="dt">Vec</span><<span class="dt">i32</span>>) -> <span class="dt">i32</span> { <span class="co">// o</span>
<span class="kw">let</span> <span class="kw">mut</span> accum = <span class="dv">0</span>; <span class="co">// |</span>
<span class="kw">for</span> i <span class="kw">in</span> v.iter() { accum += *i; } <span class="co">// |</span>
accum <span class="co">// (p.s. where is `return`?) // |</span>
} <span class="co">// * (`v` destroyed/freed)</span></code></pre></div>
</section><section id="freely-copied-values-versus-moved-objects" class="slide level2">
<h1>Freely Copied Values versus Moved Objects</h1>
<p>Integers, characters, etc use copy semantics</p>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">let</span> x: <span class="dt">i32</span> = calculate();
<span class="kw">let</span> y = x;
<span class="co">// can still use `x` here</span></code></pre></div>
<p>Structured data uses move semantics by default</p>
<ul>
<li>Compiler checks attempts to opt-in to <code>Copy</code> "interface"
<ul>
<li>("interface", aka "trait bound" in Rust)</li>
</ul></li>
</ul>
</section><section id="moved-data-errors" class="slide level2">
<h1><a href="http://is.gd/aYKrYd">Moved data errors</a></h1>
<div class="sourceCode"><pre class="sourceCode rust compile_error"><code class="sourceCode rust"><span class="at">#[</span>test<span class="at">]</span>
<span class="kw">fn</span> demo_owned_vs_copied() {
<span class="kw">let</span> moving_value = <span class="pp">vec!</span>[<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>];
<span class="kw">let</span> copied_value = <span class="dv">17</span>;
<span class="kw">let</span> tuple = (moving_value, copied_value);
<span class="pp">println!</span>(<span class="st">"copied_value: {:?}"</span>, copied_value);
<span class="pp">println!</span>(<span class="st">"moving_value: {:?}"</span>, moving_value);
}</code></pre></div>
<pre class="error_message fragment"><code>error: use of moved value: `moving_value` [E0382]
println!("moving_value: {:?}", moving_value);
^~~~~~~~~~~~
note: `moving_value` moved here because it has type
`collections::vec::Vec<i32>`, which is non-copyable
let tuple = (moving_value, copied_value);
^~~~~~~~~~~~</code></pre>
</section><section id="moves-insufficient-on-their-own" class="slide level2">
<h1><a href="http://is.gd/qwc0iq">Moves insufficient on their own</a></h1>
<p>Imagine programming without reuse</p>
<div class="sourceCode"><pre class="sourceCode rust compile_error"><code class="sourceCode rust"><span class="at">#[</span>test<span class="at">]</span>
<span class="kw">fn</span> moves_insufficient() {
<span class="kw">let</span> vec = expensive_vector_computation();
<span class="kw">let</span> result1 = some_vec_calculation(vec); <span class="co">// <-- `vec` moved here</span>
<span class="kw">let</span> result2 = other_calculation(vec); <span class="co">// oops, `vec` is *gone*</span>
combine(result1, result2);
}</code></pre></div>
<!--
```rust
fn expensive_vector_computation() -> Vec<i32> { vec![] }
fn some_vec_calculation<T>(t: T) { }
fn other_calculation<T>(t: T) { }
fn combine(x: (), y: ()) { }
```
-->
<pre class="fragment error_message"><code>error: use of moved value: `vec` [E0382]
let result2 = other_calculation(vec); // oops
^~~
note: `vec` moved here because it has type
`collections::vec::Vec<i32>`, which is non-copyable
let result1 = some_vec_calculation(vec); // <-- `vec` moved here
^~~</code></pre>
</section></section>
<section><section id="learning-to-share" class="titleslide slide level1 center"><h1>Learning to Share</h1></section><section id="borrowing-1" class="slide level2 center">
<h1><a href="http://is.gd/ez9JrK">Borrowing</a></h1>
<p><em>Lend</em> references to values</p>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="at">#[</span>test<span class="at">]</span>
<span class="kw">fn</span> hooray_for_borrows() {
<span class="kw">let</span> vec = expensive_vector_computation();
<span class="kw">let</span> result1 = some_vec_calculation(&vec); <span class="co">// <-- lend out `vec`</span>
<span class="kw">let</span> result2 = other_calculation(&vec); <span class="co">// <-- lend again, no prob</span>
combine(result1, result2);
} <span class="co">// (`vec` is destroyed/freed aka "dropped" here)</span></code></pre></div>
<pre class="fragment"><code> &vec
~~~~
|
a borrow expression</code></pre>
</section><section id="mo-features-mo-problems" class="slide level2 center">
<h1>Mo' features, mo' problems</h1>
<ul>
<li><p>Why are safety violations generally hard to detect?</p></li>
<li><p>It is due to <em>aliasing</em></p></li>
<li><p>Borrows <em>reintroduce</em> aliasing</p></li>
</ul>
<h3 id="q-how-to-ensure-safety-in-presence-of-aliasing" class="fragment">Q: How to ensure safety in presence of aliasing?</h3>
<h3 id="a-restrict-the-aliasing" class="fragment">A: Restrict the aliasing</h3>
</section><section id="restricted-aliasing" class="slide level2 center">
<h1>Restricted aliasing</h1>
<p>Analogy: RW-lock</p>
<ul>
<li><p>Many readers at once, <em>or</em> one writer with exclusive access</p></li>
<li><p>Read-only operations do not require exclusive access</p></li>
<li><p>Exclusive access requires there are no other readers</p></li>
</ul>
<p>Rust uses similar model (but at compile-time) for borrows</p>
</section><section id="the-family-of-types" class="slide level2">
<h1>The Family of Types</h1>
<ul>
<li><p><code>T</code>: base type. Moves, unless bounded by <code>Copy</code> trait</p></li>
<li><p><code>&T</code>: shared ref, "read-only" access; copyable</p>
<ul>
<li><p>programmer (+ compiler) must assumed aliased</p></li>
<li><p>(i.e. "many readers")</p></li>
</ul></li>
<li><p><code>&mut T</code>: "mutable" ref, exclusive access; non-copy</p>
<ul>
<li><p>assured unaliased</p></li>
<li><p>(i.e. "at most one writer")</p></li>
</ul></li>
</ul>
</section></section>
<section><section id="concrete-examples-of-types" class="titleslide slide level1 center"><h1>Concrete Examples of Types</h1></section><section id="readin-writin-and-transfern" class="slide level2">
<h1><a href="http://is.gd/QRmpaH">readin', writin', and transfer'n</a></h1>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">fn</span> read(v: &<span class="dt">Vec</span><<span class="dt">String</span>>) -> <span class="dt">String</span> {
<span class="kw">let</span> first: &<span class="dt">String</span> = &v[<span class="dv">0</span>]; <span class="co">// borrow ref to first elem</span>
<span class="pp">println!</span>(<span class="st">"v[0]: {}"</span>, first);
<span class="kw">return</span> first.clone();
}</code></pre></div>
<div class="fragment">
<!-- TODO: show in future slide how returning &str breaks down) -->
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">fn</span> modify(v: &<span class="kw">mut</span> <span class="dt">Vec</span><<span class="dt">String</span>>, name: &<span class="dt">str</span>) {
<span class="kw">let</span> freshly_created = <span class="pp">format!</span>(<span class="st">"Hello {}"</span>, name);
v.push(freshly_created);
}</code></pre></div>
</div>
<div class="fragment">
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">fn</span> consume(v: <span class="dt">Vec</span><<span class="dt">String</span>>) -> <span class="dt">String</span> {
<span class="kw">for</span> s <span class="kw">in</span> v { <span class="kw">return</span> s; }
<span class="pp">panic!</span>(<span class="st">"v was empty?!?"</span>);
}</code></pre></div>
</div>
</section><section id="calls-to-the-three-variants" class="slide level2">
<h1><a href="http://is.gd/QRmpaH">Calls to the three variants</a></h1>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">fn</span> read(v: &<span class="dt">Vec</span><<span class="dt">String</span>>) -> <span class="dt">String</span> { ... }
<span class="kw">fn</span> modify(v: &<span class="kw">mut</span> <span class="dt">Vec</span><<span class="dt">String</span>>, name: &<span class="dt">str</span>) { ... }
<span class="kw">fn</span> consume(v: <span class="dt">Vec</span><<span class="dt">String</span>>) -> <span class="dt">String</span> { ... }</code></pre></div>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">fn</span> user_input() -> <span class="dt">String</span> { <span class="pp">format!</span>(<span class="st">"World"</span>) }
<span class="at">#[</span>test<span class="at">]</span>
<span class="kw">fn</span> demo() {
<span class="kw">let</span> <span class="kw">mut</span> v: <span class="dt">Vec</span><<span class="dt">String</span>> = <span class="pp">vec!</span>[user_input()];
<span class="kw">let</span> first = read(&v).clone();
modify(&<span class="kw">mut</span> v, &first);
consume(v);
}</code></pre></div>
</section></section>
<section><section id="more-on-scopes" class="titleslide slide level1 center"><h1>More on Scopes</h1></section><section id="borrowing-immutably" class="slide level2" data-transition="fade-out">
<h1><a href="http://is.gd/oeTVPs">Borrowing (immutably)</a></h1>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="at">#[</span>test<span class="at">]</span>
<span class="kw">fn</span> show_some_borrows() {
<span class="kw">let</span> v1 = <span class="pp">vec!</span>[<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>];
<span class="kw">let</span> v2 = <span class="pp">vec!</span>[<span class="dv">4</span>, <span class="dv">5</span>, <span class="dv">6</span>];
<span class="kw">let</span> r1 = &v1;
<span class="kw">let</span> r2 = &v2;
foo(r1);
foo(r2);
}</code></pre></div>
<!-- -->
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">fn</span> foo<<span class="ot">'a</span>>(v: &<span class="ot">'a</span> <span class="dt">Vec</span><<span class="dt">i32</span>>) { <span class="pp">println!</span>(<span class="st">"v[1]: {}"</span>, v[<span class="dv">1</span>]); }</code></pre></div>
<p><code>&v1</code> and <code>&v2</code> are <em>borrowing</em> <code>v1</code> and <code>v2</code>.</p>
</section><section id="scopes-and-lifetimes" class="slide level2" data-transition="fade-in">
<h1><a href="http://is.gd/7uHned">Scopes and Lifetimes</a></h1>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="at">#[</span>test<span class="at">]</span>
<span class="kw">fn</span> show_some_lifetimes() {
<span class="kw">let</span> v1 = <span class="pp">vec!</span>[<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>]; <span class="co">// +</span>
<span class="kw">let</span> v2 = <span class="pp">vec!</span>[<span class="dv">4</span>, <span class="dv">5</span>, <span class="dv">6</span>]; <span class="co">// + |</span>
<span class="co">// | |</span>
<span class="kw">let</span> r1 = &v1; <span class="co">// + | |</span>
<span class="kw">let</span> r2 = &v2; <span class="co">// + | | |</span>
foo(r1); <span class="co">// | | | |</span>
foo(r2); <span class="co">// 'r2 'r1 'v2 'v1</span>
<span class="co">// | | | |</span>
} <span class="co">// * * * *</span></code></pre></div>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">fn</span> foo<<span class="ot">'a</span>>(v: &<span class="ot">'a</span> <span class="dt">Vec</span><<span class="dt">i32</span>>) { <span class="pp">println!</span>(<span class="st">"v[1]: {}"</span>, v[<span class="dv">1</span>]); }</code></pre></div>
<p>Each borrow selects "appropriate" lifetime <code>'a</code>.</p>
</section><section id="borrow-checking-prevents-errors" class="slide level2" data-transition="fade-out">
<h1><a href="http://is.gd/bRKjWu">Borrow Checking Prevents Errors</a></h1>
<div class="sourceCode"><pre class="sourceCode rust compile_error"><code class="sourceCode rust"><span class="kw">fn</span> borrow_checking_prevents_errors() {
<span class="kw">let</span> v1 = <span class="pp">vec!</span>[<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>]; <span class="co">// +</span>
<span class="co">// |</span>
<span class="kw">let</span> r1 = &v1; <span class="co">// + 'v1</span>
<span class="co">// | |</span>
consume(v1); <span class="co">// 'r1 (moved)</span>
foo(r1); <span class="co">// |</span>
} <span class="co">// *</span></code></pre></div>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"> <span class="kw">fn</span> foo<<span class="ot">'a</span>>(v: &<span class="ot">'a</span> <span class="dt">Vec</span><<span class="dt">i32</span>>) { <span class="pp">println!</span>(<span class="st">"v[1]: {}"</span>, v[<span class="dv">1</span>]); }
<span class="kw">fn</span> consume(v: <span class="dt">Vec</span><<span class="dt">i32</span>>) { <span class="co">/* `v` *dropped* at scope end */</span> }</code></pre></div>
<p><code>foo(r1)</code> attempts an indirect read of <code>v1</code></p>
<pre class="fragment"><code>error: cannot move out of `v1` because it is borrowed
consume(v1);
^~
note: borrow of `v1` occurs here
let r1 = &v1;
^~</code></pre>
</section><section id="lifetimes-and-lexical-scope" class="slide level2" data-transition="fade-in">
<h1><a href="http://is.gd/IA6Vlj">Lifetimes and Lexical Scope</a></h1>
<div class="sourceCode"><pre class="sourceCode rust compile_error"><code class="sourceCode rust"><span class="kw">fn</span> borrow_checking_may_seem_simple_minded() {
<span class="kw">let</span> v1 = <span class="pp">vec!</span>[<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>]; <span class="co">// +</span>
<span class="co">// |</span>
<span class="kw">let</span> r1 = &v1; <span class="co">// + 'v1</span>
<span class="co">// | |</span>
consume(v1); <span class="co">// 'r1 (moved)</span>
<span class="co">// (no call to read) // |</span>
} <span class="co">// *</span></code></pre></div>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"> <span class="kw">fn</span> foo<<span class="ot">'a</span>>(v: &<span class="ot">'a</span> <span class="dt">Vec</span><<span class="dt">i32</span>>) { <span class="pp">println!</span>(<span class="st">"v[1]: {}"</span>, v[<span class="dv">1</span>]); }
<span class="kw">fn</span> consume(v: <span class="dt">Vec</span><<span class="dt">i32</span>>) { }</code></pre></div>
<pre><code>error: cannot move out of `v1` because it is borrowed
consume(v1);
^~
note: borrow of `v1` occurs here
let r1 = &v1;
^~</code></pre>
<p>(artifact of lexical-scope based implementation)</p>
</section><section id="built-on-lexical-scopes-but-non-trivial" class="slide level2" data-transition="slide-in fade-out">
<h1><a href="http://is.gd/aJR3jP">Built on lexical scopes, but non-trivial</a></h1>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="at">#[</span>test<span class="at">]</span>
<span class="kw">fn</span> copying_can_extend_a_borrows_lifetime_1() {
<span class="kw">fn</span> foo<<span class="ot">'a</span>>(v: &<span class="ot">'a</span> <span class="dt">Vec</span><<span class="dt">i32</span>>) { <span class="pp">println!</span>(<span class="st">"v[1]: {}"</span>, v[<span class="dv">1</span>]); }
<span class="kw">let</span> v1 = <span class="pp">vec!</span>[<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>]; <span class="co">// +</span>
<span class="kw">let</span> v2 = <span class="pp">vec!</span>[<span class="dv">4</span>, <span class="dv">5</span>, <span class="dv">6</span>]; <span class="co">// | +</span>
<span class="kw">let</span> r2 = { <span class="co">// | |</span>
<span class="kw">let</span> r1 = &v1; <span class="co">// + | |</span>
<span class="co">// ~~~ <--- A // | | |</span>
foo(r1); <span class="co">// 'r1 | |</span>
&v2 <span class="co">// | 'v1 'v2</span>
}; <span class="co">// * + | |</span>
<span class="co">// (maybe mutate `v1` // | | |</span>
<span class="co">// here someday?) // | | |</span>
<span class="co">// 'r2 | |</span>
foo(r2); <span class="co">// | | |</span>
} <span class="co">// * * *</span></code></pre></div>
<p>How long should the borrow <code>&v1</code> last?</p>
<aside class="notes">
<p>In this case, the borrow marked "A" only needs to last long enough for the call to <code>foo(r1)</code>; after that point, the borrow is never needed.</p>
</aside>
</section><section id="built-on-lexical-scopes-but-non-trivial-1" class="slide level2" data-transition="fade-in slide-out">
<h1><a href="http://is.gd/Kse2Gz">Built on lexical scopes, but non-trivial</a></h1>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="at">#[</span>test<span class="at">]</span>
<span class="kw">fn</span> copying_can_extend_a_borrows_lifetime_2() {
<span class="kw">fn</span> foo<<span class="ot">'a</span>>(v: &<span class="ot">'a</span> <span class="dt">Vec</span><<span class="dt">i32</span>>) { <span class="pp">println!</span>(<span class="st">"v[1]: {}"</span>, v[<span class="dv">1</span>]); }
<span class="kw">let</span> v1 = <span class="pp">vec!</span>[<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>]; <span class="co">// +</span>
<span class="kw">let</span> v2 = <span class="pp">vec!</span>[<span class="dv">4</span>, <span class="dv">5</span>, <span class="dv">6</span>]; <span class="co">// | +</span>
<span class="kw">let</span> r2 = { <span class="co">// | |</span>
<span class="kw">let</span> r1 = &v1; <span class="co">// + | |</span>
<span class="co">// ~~~ <--- A // | | |</span>
foo(r1); <span class="co">// 'r1 | |</span>
r1 <span class="co">// <--------- B // | 'v1 'v2</span>
}; <span class="co">// * + | |</span>
<span class="co">// (maybe mutate `v1` // | | |</span>
<span class="co">// here someday?) // | | |</span>
<span class="co">// 'r2 | |</span>
foo(r2); <span class="co">// | | |</span>
} <span class="co">// * * *</span></code></pre></div>
<p>How long should the borrow <code>&v1</code> last now?</p>
<aside class="notes">
<p>In this case, the borrow marked "A" needs to last longer! The value of <code>r1</code> is being copied into <code>r2</code> on the line marked "B", so the borrow marked "A" needs to include the scope of both <code>'r1</code> and <code>'r2</code>.</p>
<p>Regarding that "someday" comment: http://is.gd/rRPVe2</p>
</aside>
</section><section id="imm-borrows-can-be-copied-freely" class="slide level2" data-transition="fade-out">
<h1>imm-borrows: can be copied freely</h1>
<p>(super super useful to be able to share readable data!)</p>
</section><section id="imm-borrows-can-be-copied-freely-1" class="slide level2" data-transition="fade-in fade-out">
<h1><a href="http://is.gd/MioaBw">imm-borrows: can be copied freely</a></h1>
<p>Implications:</p>
<ul>
<li>must assume aliased (perhaps by another thread)</li>
<li>therefore <em>not safe</em> to mutate in general</li>
</ul>
<div class="sourceCode"><pre class="sourceCode rust compile_error"><code class="sourceCode rust"><span class="at">#[</span>test<span class="at">]</span>
<span class="kw">fn</span> demo_cannot_mutate_imm_borrow() {
<span class="kw">let</span> <span class="kw">mut</span> v1 = <span class="pp">vec!</span>[<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>];
<span class="kw">let</span> b = &v1;
<span class="kw">let</span> (b1, b2, b3) = (b, b, b);
try_modify(b);
<span class="pp">println!</span>(<span class="st">"v1: {:?}"</span>, v1);
}
<span class="kw">fn</span> try_modify(v: &<span class="dt">Vec</span><<span class="dt">i32</span>>) {
v.push(<span class="dv">4</span>);
}</code></pre></div>
<pre class="fragment error_message"><code>error: cannot borrow immutable borrowed content `*v` as mutable
v.push(4);
^</code></pre>
</section><section id="imm-borrows-can-be-copied-freely-2" class="slide level2" data-transition="fade-in slide-out">
<h1><a href="http://is.gd/MioaBw">imm-borrows: can be copied freely</a></h1>
<p>Implications:</p>
<ul>
<li>must assume aliased (perhaps by another thread)</li>
<li>therefore <em>not safe</em> to mutate in general</li>
</ul>
<div class="sourceCode"><pre class="sourceCode rust compile_error"><code class="sourceCode rust"><span class="at">#[</span>test<span class="at">]</span>
<span class="kw">fn</span> demo_cannot_mutate_imm_borrow() {
<span class="kw">let</span> <span class="kw">mut</span> v1 = <span class="pp">vec!</span>[<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>];
<span class="kw">let</span> b = &v1;
<span class="kw">let</span> (b1, b2, b3) = (b, b, b);
try_modify(b);
<span class="pp">println!</span>(<span class="st">"v1: {:?}"</span>, v1);
}
<span class="kw">fn</span> try_modify(v: &<span class="dt">Vec</span><<span class="dt">i32</span>>) {
v.push(<span class="dv">4</span>);
}</code></pre></div>
<pre><code>WHAT
A
BUMMER!!!</code></pre>
</section><section id="my-precious-imperative-algorithms" class="slide level2 center">
<h1>my precious imperative algorithms!</h1>
</section><section id="mut-borrows" class="slide level2 center">
<h1><a href="http://is.gd/FWAPCw"><code class="sourceCode rust">&<span class="kw">mut</span></code> borrows</a></h1>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="at">#[</span>test<span class="at">]</span>
<span class="kw">fn</span> demo_can_mutate_mut_borrow() {
<span class="kw">let</span> <span class="kw">mut</span> v1 = <span class="pp">vec!</span>[<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>];
modify_vec(&<span class="kw">mut</span> v1);
<span class="pp">println!</span>(<span class="st">"v1: {:?}"</span>, v1);
}
<span class="kw">fn</span> modify_vec(v: &<span class="kw">mut</span> <span class="dt">Vec</span><<span class="dt">i32</span>>) {
v.push(<span class="dv">4</span>);
}</code></pre></div>
<pre class="fragment"><code>v1: [1, 2, 3, 4]</code></pre>
</section><section id="what-does-mut-mean-crucial" class="slide level2 center left_align" data-transition="zoom-out">
<h1>What does <code class="sourceCode rust">&<span class="kw">mut</span></code> mean (crucial)</h1>
<p>For many (but not all) types, safe mutation <em>requires</em> exclusive access</p>
<div class="fragment">
<p>Any operation requiring exclusive access should either:</p>
<ul>
<li><p>take ownership, or,</p></li>
<li><p>take an <code class="sourceCode rust">&<span class="kw">mut</span></code>-reference</p></li>
</ul>
</div>
</section><section id="exclusive-access-versus-ownership" class="slide level2">
<h1><a href="http://is.gd/J5YMKs">Exclusive Access versus Ownership</a></h1>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">fn</span> take_by_value(v: <span class="dt">Vec</span><<span class="dt">i32</span>>) { <span class="kw">let</span> <span class="kw">mut</span> v = v; v.push(<span class="dv">4</span>); }
<span class="kw">fn</span> take_mut_borrow(b: &<span class="kw">mut</span> <span class="dt">Vec</span><<span class="dt">i32</span>>) { b.push(<span class="dv">10</span>); }
<span class="co">// seemingly similar in power</span></code></pre></div>
<div class="sourceCode"><pre class="sourceCode rust compile_error"><code class="sourceCode rust"><span class="at">#[</span>test<span class="at">]</span>
<span class="kw">fn</span> demo_exclusive_access_versus_ownership() {
<span class="kw">let</span> (<span class="kw">mut</span> v1, <span class="kw">mut</span> v2) = (<span class="pp">vec!</span>[<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>], <span class="pp">vec!</span>[<span class="dv">7</span>, <span class="dv">8</span>, <span class="dv">9</span>]);
take_by_value(v1);
take_mut_borrow(&<span class="kw">mut</span> v2);
<span class="pp">println!</span>(<span class="st">"v1: {:?} v2: {:?}"</span>, v1, v2);
}</code></pre></div>
<pre class="fragment error_message"><code>error: use of moved value: `v1` [E0382]
println!("v1: {:?} v2: {:?}", v1, v2);
^~
note: `v1` moved here
take_by_value(v1);
^~</code></pre>
<div class="fragment">
<p>ownership ⇒ power + responsibility (for dropping)</p>
<p><code>&mut</code> ⇒ power without responsibility; (can only <em>swap</em>)</p>
</div>
</section></section>
<section><section id="mut-safety-enforcement" class="titleslide slide level1 center"><h1><code class="sourceCode rust">&<span class="kw">mut</span></code> safety enforcement</h1></section><section id="data-has-at-most-one-mut-borrow" class="slide level2" data-transition="slide-in fade-out">
<h1><a href="http://is.gd/Z72hwM">Data has at most one <code class="sourceCode rust">&<span class="kw">mut</span></code> borrow</a></h1>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">fn</span> take2<<span class="ot">'a</span>>(v1: &<span class="ot">'a</span> <span class="kw">mut</span> <span class="dt">Vec</span><<span class="dt">i32</span>>, v2: &<span class="ot">'a</span> <span class="dt">Vec</span><<span class="dt">i32</span>>) { }</code></pre></div>
<div class="sourceCode"><pre class="sourceCode rust compile_error"><code class="sourceCode rust"><span class="at">#[</span>test<span class="at">]</span>
<span class="kw">fn</span> demo_cannot_mut_borrow_multiple_times() {
<span class="kw">let</span> <span class="kw">mut</span> v1 = <span class="pp">vec!</span>[<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>];
<span class="kw">let</span> <span class="kw">mut</span> v2 = <span class="pp">vec!</span>[<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>];
take2(&<span class="kw">mut</span> v1, &<span class="kw">mut</span> v2); <span class="co">// <-- this is okay</span>
take2(&<span class="kw">mut</span> v1, &<span class="kw">mut</span> v1);
}</code></pre></div>
<pre class="fragment error_message"><code>error: cannot borrow `v1` as mutable more than once at a time
take2(&mut v1, &mut v1);
^~
note: previous borrow of `v1` occurs here; the mutable borrow
prevents subsequent moves, borrows, or modification of
`v1` until the borrow ends
take2(&mut v1, &mut v1);
^~
</code></pre>
</section><section id="cannot-alias-mut-borrowed-data" class="slide level2" data-transition="fade">
<h1><a href="http://is.gd/MRxBeK">Cannot alias <code class="sourceCode rust">&<span class="kw">mut</span></code>-borrowed data</a></h1>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">fn</span> take2<<span class="ot">'a</span>>(v1: &<span class="ot">'a</span> <span class="kw">mut</span> <span class="dt">Vec</span><<span class="dt">i32</span>>, v2: &<span class="ot">'a</span> <span class="dt">Vec</span><<span class="dt">i32</span>>) { }</code></pre></div>
<div class="sourceCode"><pre class="sourceCode rust compile_error"><code class="sourceCode rust"><span class="at">#[</span>test<span class="at">]</span>
<span class="kw">fn</span> demo_cannot_alias_mut_borrowed_data() {
<span class="kw">let</span> <span class="kw">mut</span> v1 = <span class="pp">vec!</span>[<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>];
<span class="kw">let</span> <span class="kw">mut</span> v2 = <span class="pp">vec!</span>[<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>];
take2(&<span class="kw">mut</span> v1, &v2); <span class="co">// <-- this is okay</span>
take2(&<span class="kw">mut</span> v1, &v1);
}</code></pre></div>
<pre class="fragment error_message"><code>error: cannot borrow `v1` as immutable because it is also borrowed
as mutable
take2(&mut v1, &v1);
^~
note: previous borrow of `v1` occurs here; the mutable borrow
prevents subsequent moves, borrows, or modification of `v1`
until the borrow ends
take2(&mut v1, &v1);
^~</code></pre>
</section><section id="mut-t-is-non-copy" class="slide level2" data-transition="fade-in slide-out">
<h1><a href="http://is.gd/vBPs15"><code class="sourceCode rust">&<span class="kw">mut</span> T</code> is non-copy</a></h1>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">fn</span> take2<<span class="ot">'a</span>>(v1: &<span class="ot">'a</span> <span class="kw">mut</span> <span class="dt">Vec</span><<span class="dt">i32</span>>, v2: &<span class="ot">'a</span> <span class="dt">Vec</span><<span class="dt">i32</span>>) { }</code></pre></div>
<div class="sourceCode"><pre class="sourceCode rust compile_error"><code class="sourceCode rust"><span class="at">#[</span>test<span class="at">]</span>
<span class="kw">fn</span> demo_cannot_copy_mut_borrows() {
<span class="kw">let</span> <span class="kw">mut</span> v1 = <span class="pp">vec!</span>[<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>];
<span class="kw">let</span> b = &<span class="kw">mut</span> v1;
<span class="kw">let</span> c = b;
take2(b, c);
}</code></pre></div>
<pre class="fragment error_message"><code>error: use of moved value: `*b` [E0382]
take2(b, c);
^
note: `b` moved here because it has type
`&mut collections::vec::Vec<i32>`, which is moved by default
let c = b;
^</code></pre>
<p>(ensures exclusive access)</p>
</section></section>
<section><section id="wither-a.method" class="titleslide slide level1 center"><h1>Wither <code class="sourceCode rust">a.method()</code> ?</h1></section><section id="rust-has-methods-too" class="slide level2">
<h1><a href="http://is.gd/2r7DRl">Rust has methods too</a></h1>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">struct</span> Point { x: <span class="dt">i32</span>, y: <span class="dt">i32</span> }
<span class="kw">impl</span> Point {
<span class="kw">fn</span> distance_from_origin(&<span class="kw">self</span>) -> <span class="dt">i32</span> {
<span class="kw">let</span> Point { x, y } = *<span class="kw">self</span>;
<span class="kw">let</span> sum = (x*x + y*y) <span class="kw">as</span> <span class="dt">f64</span>;
sum.sqrt() <span class="kw">as</span> <span class="dt">i32</span>
}
}
<span class="at">#[</span>test<span class="at">]</span>
<span class="kw">fn</span> demo_dist() {
<span class="kw">let</span> p = Point { x: <span class="dv">3</span>, y: <span class="dv">4</span> };
<span class="pp">assert_eq!</span>(<span class="dv">5</span>, p.distance_from_origin());
}</code></pre></div>
</section><section id="method-signatures" class="slide level2 center">
<h1>Method signatures</h1>
<ul>
<li><code class="sourceCode rust"><span class="kw">self</span></code>: <em>consumes</em> receiver</li>
<li><code class="sourceCode rust">&<span class="kw">self</span></code>: <em>accesses</em> receiver</li>
<li><code class="sourceCode rust">&<span class="kw">mut</span> <span class="kw">self</span></code>: <em>mutates</em> receiver</li>
</ul>
</section><section id="method-signatures-self" class="slide level2">
<h1>Method signatures: &self</h1>
<p>Accesses receiver</p>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">enum</span> <span class="dt">Option</span><T> { <span class="cn">None</span>, <span class="cn">Some</span>(T) } <span class="co">// algebraic data! generics!</span>
<span class="kw">impl</span><T> <span class="dt">Option</span><T> {
<span class="co">// &Option<T> -> bool</span>
<span class="kw">fn</span> is_some(&<span class="kw">self</span>) -> <span class="dt">bool</span> {
<span class="kw">match</span> *<span class="kw">self</span> {
<span class="cn">Some</span>(_) => <span class="cn">true</span>,
<span class="cn">None</span> => <span class="cn">false</span>
}
}
<span class="kw">fn</span> is_none(&<span class="kw">self</span>) -> <span class="dt">bool</span> {
!<span class="kw">self</span>.is_some()
}
}</code></pre></div>
</section><section id="method-signatures-mut-self" class="slide level2">
<h1>Method signatures: &mut self</h1>
<p>"Mutates" receiver</p>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">enum</span> <span class="dt">Option</span><T> { <span class="cn">None</span>, <span class="cn">Some</span>(T) }
<span class="kw">impl</span><T> <span class="dt">Option</span><T> {
<span class="co">// &mut Option<T> -> Option<T></span>
<span class="kw">fn</span> take(&<span class="kw">mut</span> <span class="kw">self</span>) -> <span class="dt">Option</span><T> {
<span class="kw">let</span> <span class="kw">mut</span> src = <span class="cn">None</span>;
swap(<span class="kw">self</span>, &<span class="kw">mut</span> src);
src
}
}</code></pre></div>
</section><section id="method-signatures-self-1" class="slide level2">
<h1>Method signatures: self</h1>
<p><span class="strike">"Consumes"</span> Takes ownership of receiver</p>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">impl</span><T> <span class="dt">Option</span><T> {
<span class="co">// Option<T> -> T</span>
<span class="kw">fn</span> unwrap_or(<span class="kw">self</span>, default: T) -> T {
<span class="kw">match</span> <span class="kw">self</span> {
<span class="cn">Some</span>(x) => x,
<span class="cn">None</span> => default
}
} <span class="co">// one of `self` or `default` dropped at end</span>
}</code></pre></div>
</section><section class="slide level2">
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">impl</span><T> <span class="dt">Option</span><T> {
<span class="kw">fn</span> is_some(&<span class="kw">self</span>) -> <span class="dt">bool</span> { ... }
<span class="kw">fn</span> is_none(&<span class="kw">self</span>) -> <span class="dt">bool</span> { ... }
<span class="kw">fn</span> take(&<span class="kw">mut</span> <span class="kw">self</span>) -> <span class="dt">Option</span><T> { ... }
<span class="kw">fn</span> unwrap_or(<span class="kw">self</span>, default: T) -> T { ... }
}</code></pre></div>
<!--
```rust
#[test]
fn demo_reading_protocol() {
demo_subroutine(format!("World"));
}
```
-->
<div class="fragment">
<p>Some magic: <a href="http://is.gd/n8CaTJ">method invocations</a> automatically do borrows <em>and</em> derefs as necessary on the receiver ("auto-ref").</p>
</div>
<div class="fragment">
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">fn</span> demo_subroutine(name: <span class="dt">String</span>) {
<span class="kw">let</span> <span class="kw">mut</span> hi = <span class="cn">Some</span>(<span class="pp">format!</span>(<span class="st">"Hello {}"</span>, &name));
<span class="pp">assert!</span>(hi.is_some()); <span class="co">// this is an `&hi`</span>
<span class="kw">let</span> grabbed = hi.take(); <span class="co">// this is an `&mut hi`</span>
<span class="pp">assert!</span>(hi.is_none()); <span class="co">// this is an `&hi`</span>
<span class="co">// and this consumes `grabbed`</span>
<span class="pp">assert!</span>(&grabbed.unwrap_or(name)[<span class="dv">0.</span>.<span class="dv">5</span>] == <span class="st">"Hello"</span>);
}</code></pre></div>
</div>
</section></section>
<section><section id="for-the-c-fans-in-the-audience-smart-pointers" class="titleslide slide level1 center"><h1>For the C++ fans in the audience: Smart Pointers</h1></section><section id="smart-pointers" class="slide level2 center">
<h1>"Smart" "Pointers"</h1>
<ul>
<li><p><code>Box<T></code>: unique reference to <code>T</code> on (<code>malloc</code>/<code>free</code>-style) heap</p></li>
<li><p><code>Rc<T></code>: shared ownership, thread-local</p></li>
<li><p><code>Arc<T></code>: shared ownership, safe across threads</p></li>
</ul>
<div class="fragment">
<p>All of above deref to <code>&T</code></p>
</div>
</section><section id="deref-works-here-too" class="slide level2 center">
<h1><a href="http://is.gd/J9RKXK"><code>Deref</code> works here too</a></h1>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="at">#[</span>test<span class="at">]</span>
<span class="kw">fn</span> demo_rc_of_point() {
<span class="kw">use</span> std::rc::Rc;
<span class="kw">let</span> p1 = Rc::new(Point { x: <span class="dv">3</span>, y: <span class="dv">4</span> });
<span class="kw">let</span> p2 = p1.clone();
<span class="pp">assert_eq!</span>(<span class="dv">5</span>, p1.distance_from_origin());
<span class="pp">assert_eq!</span>(<span class="dv">5</span>, p2.distance_from_origin());
<span class="co">// p1.x = 6; // (STATIC ERROR; cannot assign Rc contents)</span>
}</code></pre></div>
</section><section id="other-deref-fun" class="slide level2">
<h1>Other Deref fun</h1>
<p><code>Box<T></code>, <code>Rc<T></code>, <code>Arc<T></code> all deref to <code>&T</code></p>
<p>But we also have things like this:</p>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">pub</span> <span class="kw">enum</span> Cow<<span class="ot">'a</span>, B> <span class="kw">where</span> B: ToOwned {
Borrowed(&<span class="ot">'a</span> B),
Owned(<B <span class="kw">as</span> ToOwned>::Owned)
}</code></pre></div>
<p>which derefs to <code>&B</code>, even if it is in the <code>Owned</code> variant.</p>
<div class="fragment">
<p>(Useful for APIs that want to delay the decision of whether to return an owned value or a borrowed reference.)</p>
</div>
</section></section>
<section><section id="lifetime-bindings" class="titleslide slide level1 center"><h1>Lifetime Bindings</h1></section><section id="lifetime-bindings-1" class="slide level2 center">
<h1><a href="http://is.gd/YUeL9J">Lifetime Bindings 1</a></h1>
<p>We saw this kind of thing before:</p>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="at">#[</span>test<span class="at">]</span>
<span class="kw">fn</span> explicit_lifetime_binding_1() {
<span class="kw">fn</span> print<<span class="ot">'a</span>>(ints: &<span class="ot">'a</span> <span class="dt">Vec</span><<span class="dt">i32</span>>) {
<span class="pp">println!</span>(<span class="st">"v_1: {}"</span>, ints[<span class="dv">1</span>]);
}
<span class="kw">let</span> v1 = <span class="pp">vec!</span>[<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>];
print(&v1)
}</code></pre></div>
</section><section id="lifetime-bindings-2" class="slide level2" data-transition="fade-out">
<h1><a href="http://is.gd/VUhzbN">Lifetime Bindings 2</a></h1>
<p>You can bind distinct lifetimes:</p>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="at">#[</span>test<span class="at">]</span>
<span class="kw">fn</span> explicit_lifetime_binding_2() {
<span class="kw">fn</span> print<<span class="ot">'a</span>, <span class="ot">'b</span>>(ptrs: &<span class="ot">'a</span> <span class="dt">Vec</span><&<span class="ot">'b</span> <span class="dt">i32</span>>) {
<span class="pp">println!</span>(<span class="st">"v_1: {}"</span>, ptrs[<span class="dv">1</span>]);
}
<span class="kw">let</span> one = <span class="dv">1</span>;
<span class="kw">let</span> two = <span class="dv">2</span>;
<span class="kw">let</span> three = <span class="dv">3</span>;
<span class="kw">let</span> four = <span class="dv">4</span>;
<span class="kw">let</span> v1 = <span class="pp">vec!</span>[&one, &two, &three];
print(&v1)
}</code></pre></div>
</section><section id="lifetime-bindings-3" class="slide level2" data-transition="fade">
<h1><a href="http://is.gd/I22UHF">Lifetime Bindings 3</a></h1>
<p>Encode constraints by reusing same lifetime:</p>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="at">#[</span>test<span class="at">]</span>
<span class="kw">fn</span> explicit_lifetime_binding_3() {
<span class="kw">fn</span> print<<span class="ot">'a</span>, <span class="ot">'b</span>>(ptrs: &<span class="ot">'a</span> <span class="kw">mut</span> <span class="dt">Vec</span><&<span class="ot">'b</span> <span class="dt">i32</span>>, ptr: &<span class="ot">'b</span> <span class="dt">i32</span>) {
<span class="pp">println!</span>(<span class="st">"v_1: {}"</span>, ptrs[<span class="dv">1</span>]);
ptrs.push(ptr);
}
<span class="kw">let</span> one = <span class="dv">1</span>;
<span class="kw">let</span> two = <span class="dv">2</span>;
<span class="kw">let</span> three = <span class="dv">3</span>;
<span class="kw">let</span> four = <span class="dv">4</span>;
<span class="kw">let</span> <span class="kw">mut</span> v1 = <span class="pp">vec!</span>[&one, &two, &three];
print(&<span class="kw">mut</span> v1, &four);
}</code></pre></div>
</section><section id="lifetime-bindings-4" class="slide level2" data-transition="fade-in">
<h1><a href="http://is.gd/5wOydB">Lifetime Bindings 4</a></h1>
<p>Encode constraints by reusing same lifetime:</p>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="at">#[</span>test<span class="at">]</span>
<span class="kw">fn</span> explicit_lifetime_binding_4() {
<span class="kw">fn</span> print<<span class="ot">'a</span>, <span class="ot">'b</span>>(ptrs: &<span class="ot">'a</span> <span class="kw">mut</span> <span class="dt">Vec</span><&<span class="ot">'b</span> <span class="dt">i32</span>>, ptr: &<span class="ot">'b</span> <span class="dt">i32</span>) {
<span class="pp">println!</span>(<span class="st">"v_1: {}"</span>, ptrs[<span class="dv">1</span>]);<span class="co">//~~~ ~~~</span>
ptrs.push(ptr); <span class="co">// | |</span>
} <span class="co">// this must match that,</span>
<span class="kw">let</span> one = <span class="dv">1</span>; <span class="co">// otherwise push is bogus</span>
<span class="kw">let</span> two = <span class="dv">2</span>;
<span class="kw">let</span> three = <span class="dv">3</span>;
<span class="kw">let</span> four = <span class="dv">4</span>;
<span class="kw">let</span> <span class="kw">mut</span> v1 = <span class="pp">vec!</span>[&one, &two, &three];
print(&<span class="kw">mut</span> v1, &four);
}</code></pre></div>
</section><section id="lifetime-bindings-5" class="slide level2" data-transition="fade-in">
<h1><a href="http://is.gd/JX2zpy">Lifetime Bindings 5</a></h1>
<p>Compiler catches missing necessary constraints:</p>
<div class="sourceCode"><pre class="sourceCode rust compile_error"><code class="sourceCode rust"><span class="at">#[</span>test<span class="at">]</span>
<span class="kw">fn</span> explicit_lifetime_binding_5() {
<span class="kw">fn</span> print<<span class="ot">'a</span>, <span class="ot">'b</span>, <span class="ot">'c</span>>(ptrs: &<span class="ot">'a</span> <span class="kw">mut</span> <span class="dt">Vec</span><&<span class="ot">'b</span> <span class="dt">i32</span>>, ptr: &<span class="ot">'c</span> <span class="dt">i32</span>) {
<span class="pp">println!</span>(<span class="st">"v_1: {}"</span>, ptrs[<span class="dv">1</span>]); <span class="co">// ~~~ ~~~</span>
ptrs.push(ptr); <span class="co">// | |</span>
} <span class="co">// this must match that,</span>
<span class="kw">let</span> one = <span class="dv">1</span>; <span class="co">// otherwise push is bogus</span>
}</code></pre></div>
<pre class="fragment"><code>error: cannot infer an appropriate lifetime for automatic coercion
due to conflicting requirements
ptrs.push(ptr);
^~~
help: consider using an explicit lifetime parameter as shown:
fn print<'a, 'b>(ptrs: &'a mut Vec<&'b i32>, ptr: &'b i32)</code></pre>
</section><section id="borrowed-return-values-1" class="slide level2" data-transition="fade-out">
<h1><a href="http://is.gd/gKhfy0">Borrowed return values 1</a></h1>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">fn</span> first_n_last<<span class="ot">'a</span>>(ints: &<span class="ot">'a</span> <span class="dt">Vec</span><<span class="dt">i32</span>>) -> (&<span class="ot">'a</span> <span class="dt">i32</span>, &<span class="ot">'a</span> <span class="dt">i32</span>) {
<span class="co">// ~~~~~~~ ~~~~~~~</span>
(&ints[<span class="dv">0</span>], &ints[ints.len() - <span class="dv">1</span>])
}</code></pre></div>
<!--
TODO: Exercise idea: Try to write `fn first_and_last_mut`. Why is it impossible
in general?
-->
<div class="fragment">
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="at">#[</span>test<span class="at">]</span>
<span class="kw">fn</span> demo_borrowed_return_values() {
<span class="kw">let</span> v = <span class="pp">vec!</span>[<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>, <span class="dv">4</span>];
<span class="kw">let</span> (first, fourth) = first_n_last(&v);
<span class="pp">assert_eq!</span>(*first, <span class="dv">1</span>);
<span class="pp">assert_eq!</span>(*fourth, <span class="dv">4</span>);
}</code></pre></div>
<p>(compiler ensures borrow <code class="sourceCode rust">&v</code> lasts long enough to satisfy reads of <code>first</code> and <code>fourth</code>)</p>
</div>
</section><section id="borrowed-return-values-2" class="slide level2" data-transition="fade-in">
<h1><a href="http://is.gd/DzWgSs">Borrowed return values 2</a></h1>
<div class="sourceCode"><pre class="sourceCode rust compile_error"><code class="sourceCode rust"><span class="kw">fn</span> first_n_last<<span class="ot">'a</span>>(ints: <span class="dt">Vec</span><<span class="dt">i32</span>>) -> (&<span class="ot">'a</span> <span class="dt">i32</span>, &<span class="ot">'a</span> <span class="dt">i32</span>) {
<span class="co">// ~~~~~~~~ (hint)</span>
(&ints[<span class="dv">0</span>], &ints[ints.len() - <span class="dv">1</span>])
}</code></pre></div>
<p>Why doesn't this work?</p>
<pre class="fragment" data-fragment-index="1"><code>error: `ints` does not live long enough
(&ints[0], &ints[ints.len() - 1])
^~~~
note: reference must be valid for the lifetime 'a ...
note: ...but borrowed value is only valid for the scope of
note: parameters for function</code></pre>
<div class="fragment">
<p>caller chooses <code class="sourceCode rust"><span class="ot">'a</span></code>; <code>fn</code> body must work for any such choice</p>
<p>(Parameters dropped at scope end; won't live long enough)</p>
</div>
</section></section>
<section><section id="lifetime-elision" class="titleslide slide level1 center"><h1>Lifetime Elision</h1></section><section id="all-the-a-b-...-are-ugly" class="slide level2 center">
<h1>All the <code class="sourceCode rust"><span class="ot">'a</span></code>, <code class="sourceCode rust"><span class="ot">'b</span></code>, ... are ugly</h1>
</section><section id="lifetime-elision-1" class="slide level2" data-transition="fade-out">
<h1><a href="http://is.gd/72HT0U">Lifetime Elision 1</a></h1>
<div class="sourceCode"><pre class="sourceCode rust"><code class="sourceCode rust"><span class="at">#[</span>test<span class="at">]</span>
<span class="kw">fn</span> lifetime_elision_1() {