-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
1704 lines (1612 loc) · 71.3 KB
/
index.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 lang="en">
<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: An Introduction</title>
<link rel="stylesheet" href="dist/reset.css">
<link rel="stylesheet" href="dist/reveal.css">
<link rel="stylesheet" href="dist/theme/black.css">
<link rel="stylesheet" href="dist/theme/local.css">
<!-- Theme used for syntax highlighted code -->
<link rel="stylesheet" href="plugin/highlight/monokai.css">
</head>
<body>
<div class="reveal">
<div class="slides">
<!-- Introduction. -->
<section
data-background-gradient="linear-gradient(to bottom, #FF474C, #8B47AC)"
data-background-image="assets/cuddlyferris.svg"
data-background-size="50%"
style="text-shadow: 1px 1px 3px #0000f1"
>
<p style="font-size: larger; margin-top: 2em; margin-bottom: 3em">
<span class="rust">Rust</span>: An Introduction
</p>
<p style="font-size: medium">
by <span class="rust" style="text-decoration: line-through">Ferris the Crab</span> Todd Smith<br/>
Rust Solution Architect<br/>
Xebia Functional
</p>
<aside class="notes">
{5s}<br>
→
</aside>
</section>
<!-- Where Rust is used. -->
<section>
<p>Where is <span class="rust">Rust</span> used?</p>
<ul>
<li class="fragment fade-left">Backend</li>
<li class="fragment fade-left">Web</li>
<li class="fragment fade-left">Mobile</li>
<li class="fragment fade-left">Embedded</li>
<li class="fragment fade-left">GUI</li>
<li class="fragment fade-left">Games</li>
</ul>
<aside class="notes">
Rust is a systems programming language with great ergonomics and sweet
high-level features, suitable for<br>
→<br>
backend development,<br>
→<br>
web applications,<br>
→<br>
mobile,<br>
→<br>
embedded,<br>
→<br>
graphical user interfaces,<br>
→<br>
and even games.<br>
{3s}<br>
→<br>
</aside>
</section>
<!-- Noteworthy features of Rust. -->
<section>
<p>Noteworthy features of <span class="rust">Rust</span>:</p>
<div style="margin-left: 8em">
<ul style="display: block">
<li class="fragment fade-left" style="font-size: medium">Imperative execution</li>
</ul>
<ul class="fragment fade-left" style="display: block">
<li style="font-size: medium">Immutability by default</li>
<li style="font-size: medium">Algebraic data types</li>
<li style="font-size: medium">Higher-order functions</li>
<li style="font-size: medium">Type deduction (Hindley-Milner)</li>
<li style="font-size: medium">Traits (i.e., type classes)</li>
<li style="font-size: medium">Pattern matching</li>
</ul>
<ul style="display: block">
<li class="fragment fade-left" style="font-size: medium">Top-tier performance</li>
<li class="fragment fade-left" style="font-size: medium">Type safety</li>
<li class="fragment fade-left" style="font-size: medium">Memory safety</li>
<li class="fragment fade-left" style="font-size: medium">Metaprogramming (macros, auto-derive)</li>
<li
class="fragment fade-left-highlight-red"
style="font-size: medium; text-transform: uppercase"
>
No garbage collector!
</li>
</ul>
</div>
<aside class="notes">
Rust is an<br>
→<br>
imperative language at its core,<br>
→<br>
but borrows a lot of goodness from functional programming. Rust also provides<br>
→<br>
top-notch performance,<br>
→<br>
type safety,<br>
→<br>
and memory safety.<br>
→<br>
Rust supports metaprogramming through attributes and macros.<br>
→<br>
And incredibly, Rust does all of this without a garbage collector.<br>
{3s}<br>
→<br>
</aside>
</section>
<!-- Timeline of Rust. -->
<section>
<p>Timeline of <span class="rust">Rust</span>:</p>
<ul>
<li>
2006: Created by Graydon Hoare at Mozilla
</li>
<li class="fragment fade-left">
2009: Adopted officially at Mozilla
</li>
<li class="fragment fade-left">
2015: First stable release
</li>
<li class="fragment fade-left-highlight-red" style="text-transform: uppercase">
2022: Linux kernel, baby!
</li>
<li class="fragment fade-left">
2023: Xebia Functional opens Rust service line
</li>
</ul>
<aside class="notes">
Graydon Hoare created Rust as a personal project in 2006 while working at Mozilla.<br>
→<br>
Mozilla officially adopted the project in 2009, but<br>
→<br>
the first stable release wasn't until May 2015. Since its release, grassroots enthusiasm has brought it to<br>
Amazon, Meta, Alphabet, Microsoft, and tons of others.<br>
→<br>
Linus even welcomed it into the kernel in December 2022! But the adoption of programming languages is slow,<br>
yo, so it's only recently that Rust started spreading like wildfire.<br>
→<br>
Now that wildfire has spread to Xebia Functional.<br>
{suspend}<br>
{focus on presenter}<br>
For the next 30 minutes, that wildfire looks like this guy, Todd Smith, the new Rust Solution Architect,
laying down some Rust basics, so thanks for joining me today. Without further ado, let's see what Rust
brings to table.<br>
{resume}<br>
→<br>
</aside>
</section>
<!-- Memory safety segue. -->
<section>
<h1>MEMORY SAFETY</h1>
<p class="fragment custom fade-blur">(in C 😖)</p>
<aside class="notes">
There are a lot of things that Rust does the same as other languages, but I want to focus on what Rust does
<em>differently</em>.<br>
It's typical to spend a lot of time <em>thinking</em> about data ownership when using a systems programming
language,<br>
→<br>
but usually the language doesn't have any useful features for <em>actually managing</em> data ownership.<br>
→<br>
</aside>
</section>
<!-- Splint code. -->
<section data-auto-animate="splint">
<div class="r-stack">
<pre><code class="language-cpp" data-trim data-line-numbers data-noescape>
extern /*@only@*/ int* glob;
/*@only@*/ int* f (
/*@only@*/ int* x,
int* y,
int* z
) /*@globals glob@*/
{
int* m = (int*) malloc(sizeof(int));
glob = y;
free(x);
*m = *x;
return z;
}
</code></pre>
</div>
<p>Splint</p>
<aside class="notes">
Back in the bad old days of C, if you wanted memory safety, you could bust out third-party tools like Splint
and Valgrind and then instrument your code with cheesy annotations and special wrapper calls.<br>
→<br>
</aside>
</section>
<!-- Splint feedback. -->
<section data-auto-animate="splint">
<div class="r-stack">
<pre style="margin-top: -40px; margin-left: -10px">
<code class="language-cpp" data-trim data-line-numbers data-noescape>
extern /*@only@*/ int* glob;
/*@only@*/ int* f (
/*@only@*/ int* x,
int* y,
int* z
) /*@globals glob@*/
{
int* m = (int*) malloc(sizeof(int));
glob = y;
free(x);
*m = *x;
return z;
}
</code>
</pre>
<pre>
<code data-trim data-noescape style="background-color: #444444">
> splint only.c
only.c:10: Only storage glob (type int *) not released
before assignment: glob = y
only.c:1: Storage glob becomes only
only.c:11: Implicitly temp storage y assigned to only:
glob = y
only.c:12: Dereference of possibly null pointer m: *m
only.c:9: Storage m may become null
only.c:12: Variable x used after being released
only.c:11: Storage x released
only.c:13: Implicitly temp storage z returned as only: z
only.c:13: Fresh storage m not released before return
only.c:9: Fresh storage m allocated
</code>
</pre>
</div>
<p>Splint</p>
<aside class="notes">
But you only got as much support as you paid for with your own effort and diligence; you got nada from the
compiler. And you still expected to spend hours, days, maybe weeks, in front of transcripts and debuggers.<br>
→<br>
</aside>
</section>
<!-- Possession is 9/10 of the law. -->
<section data-auto-animate="law">
<a data-id="image" href="https://commons.wikimedia.org/w/index.php?curid=59794940">
<img
src="assets/Hammurabi%20Speaks.png"
alt="By Mbzt - Own work, CC BY 3.0, https://commons.wikimedia.org/w/index.php?curid=59794940"
style="width: 50%; height: auto">
</a>
<p data-id="lawgiver">Hammurabi the Lawgiver</p>
<aside class="notes">
They say that possession is nine tenths of the law,<br>
→<br>
</aside>
</section>
<!-- Possession is 9/10 of the law. -->
<section
data-auto-animate="law"
data-background-gradient="linear-gradient(to bottom, #FF474C, #8B47AC)"
>
<img
data-id="image"
src="assets/Ferris%20Speaks.png"
alt="Ferris Speaks"
style="width: 50%; height: auto"
>
<p data-id="lawgiver"><span style="text-decoration: line-through">Hammurabi</span> <span class="rust">Ferris</span> the Lawgiver</p>
<aside class="notes">
but in Rust, it's more like the whole of the law. Rust bakes in all the support that C desperately needs but
never had. Ownership is built directly into the type system, so type safety <em>is</em> memory safety.<br>
→<br>
</aside>
</section>
<!-- Introducing ownership. -->
<section>
<dl>
<dt>Ownership</dt>
<dd class="fragment">The <span class="rust">obligation</span> to destroy a value <em>when it goes out of scope</em>.</dd>
</dl>
<aside class="notes">
So, what <em>is</em> ownership, exactly?<br>
→<br>
Well, it's basically the obligation to destroy something when it goes out of scope.<br>
→<br>
</aside>
</section>
<!-- Demonstrate ownership. -->
<section>
<pre style="font-size: medium"><code class="language-rust" data-trim data-line-numbers data-noescape>
struct Wrapped<T>(
T // Owner of some `T`
);
enum Either<A, B> {
A(A), // Owner of some `A`
B(B), // Owner of some `B`
}
fn main() {
let i = 5; // Owner of `5`
let w = Wrapped(i); // Owner of `Wrapped(5)`; `i` still lives
let a = Either::A(w); // Owner of `Either::A`; `w` destroyed by move
let _x = f(a); // Owner of some `Either`; `a` destroyed by move
} // `_x` destroyed by end of block
fn f<A>(
e: Either<Wrapped<A>, Wrapped<A>> // Owner of some `Either`
) -> Either<Wrapped<A>, Wrapped<A>> { // Returns ownership of some `Either`
match e {
Either::A(a) => // `a` is owner of `Wrapped`; `e` destroyed by move
Either::B(a), // Temporary is owner of `Either::B`
Either::B(b) => // `a` is owner of `Wrapped`; `e` destroyed by move
Either::A(b) // Temporary is owner of `Either::A`
} // Return ownership of some `Either`
}
</code></pre>
<p>Ownership</p>
<aside class="notes">
I know that was so 2 minutes ago, but remember how I said that Rust doesn't need a garbage collector?
Instead, the Rust compiler has a <em>borrow checker</em>, a built-in static analyzer that tracks ownership
of values. The borrow checker ensures that Rust always knows when to destroy an object. In the vast majority
of cases, the borrow checker can <em>statically</em> determine where to insert the destructor call; in the
few cases where it can't, the borrow checker can defer ownership tracking until runtime. There's no escaping
the borrow checker, and that's a good thing!<br>
Ownership always accompanies introduction of a value. In other words, when code mentions a literal or
instantiates a struct or enum, then some variable, formal parameter, field, or temporary becomes the owner
of the new value. And the owner is responsible for the value's eventual destruction, when the owner goes out
of scope.<br>
But the owner can also delegate that responsibility, by assigning the value to another variable or field or
by giving ownership to another function or method. Whenever you see a punctuation-free type annotation on a
formal parameter of a function or method signature, it means that the formal parameter assumes ownership of
the passed value. After giving the value away, the owner becomes defunct — it hasn't technically gone out of
scope, but the compiler will signal an error if you mention it again.<br>
For simple values, like booleans and numbers, the compiler makes a copy, and the result is two owned values
— one associated with the original binding, one with the new binding.<br>
For more complex values, passing the value transfers ownership to the new binding. After the transfer, you
can't use the original binding anymore — no takebacks!<br>
→<br>
</aside>
</section>
<!-- Deriving Copy. -->
<section>
<div class="r-stack">
<img
class="fragment major-fade-out"
src="assets/Spy%20Shhh.png"
alt="Spy Shhh"
style="width: 60%; height: auto"
data-fragment-index="1"
>
<pre class="fragment" style="font-size: medium" data-fragment-index="1">
<code class="language-rust" data-trim data-line-numbers data-noescape>
#[derive(Copy)] // Instances will be copied rather than moved
struct Point3D {
x: f64,
y: f64,
z: f64
}
</code>
</pre>
</div>
<p>Deriving the <code>Copy</code> trait</p>
<aside class="notes">
Full disclosure: you can opt into copying for your own types, but that's out of scope right now;<br>
→<br>
I need to leave stuff for future talks, capisce?<br>
{3s}<br>
→<br>
</aside>
</section>
<!-- Demonstrate ownership, redux. -->
<section>
<pre style="font-size: medium"><code class="language-rust" data-trim data-line-numbers data-noescape>
struct Wrapped<T>(
T // Owner of some `T`
);
enum Either<A, B> {
A(A), // Owner of some `A`
B(B), // Owner of some `B`
}
fn main() {
let i = 5; // Owner of `5`
let w = Wrapped(i); // Owner of `Wrapped(5)`; `i` still lives
let a = Either::A(w); // Owner of `Either::A`; `w` destroyed by move
let _x = f(a); // Owner of some `Either`; `a` destroyed by move
} // `_x` destroyed by end of block
fn f<A>(
e: Either<Wrapped<A>, Wrapped<A>> // Owner of some `Either`
) -> Either<Wrapped<A>, Wrapped<A>> { // Returns ownership of some `Either`
match e {
Either::A(a) => // `a` is owner of `Wrapped`; `e` destroyed by move
Either::B(a), // Temporary is owner of `Either::B`
Either::B(b) => // `a` is owner of `Wrapped`; `e` destroyed by move
Either::A(b) // Temporary is owner of `Either::A`
} // Return ownership of some `Either`
}
</code></pre>
<p>Ownership</p>
<aside class="notes">
Anyway, taken together, these rules mean that every value has exactly one owner. And since the owner has the
obligation to destroy the value, it means that each value will be destroyed at most one time.<br>
→<br>
</aside>
</section>
<!-- Double free in C. -->
<section>
<pre><code class="language-cpp" data-trim data-line-numbers data-noescape>
int* x = (int*) malloc(sizeof(int)); // Allocate
free(x); // Single free - good
free(x); // Double free - bad
</code></pre>
<p>C loves double free — no error 🤦</p>
<aside class="notes">
If you've spent a lot of time with C or C++, you've probably already drawn the conclusion: by enforcing
linearity of ownership,<br>
→<br>
</aside>
</section>
<!-- Double free in Rust. -->
<section>
<pre><code class="language-rust" data-trim data-line-numbers data-noescape data-ln-start-from="2">
let x = SomeStruct::default(); // Allocate
drop(x); // Single free - good
drop(x); // Double free - forbidden!
</code></pre>
<pre class="console" style="font-size: medium">
<span class="command">➜ cargo</span> build
<span class="command">Compiling</span> double-free v0.1.0 (/double-free)
<span class="error">error[E0382]</span>: use of moved value: `x`
<span class="advice">--></span> double-free/src/main.rs:4:10
<span class="advice">|</span>
<span class="advice">2 |</span> let x = SomeStruct::default();
<span class="advice">| - move occurs because `x` has type `SomeStruct`, which does not implement the `Copy` trait</span>
<span class="advice">3 |</span> drop(x);
<span class="advice">| - value moved here</span>
<span class="advice">4 |</span> drop(x);
<span class="advice">|</span> <span class="error">^ value used here after move</span>
For more information about this error, try `rustc --explain E0382`.
<span class="error">error</span>: could not compile `double-free` (bin "double-free") due to previous error
</pre>
<p><span class="rust">Rust</span> hates double free — compiler error 🙌</p>
<aside class="notes">
Rust statically prevents the memory error called <em>double free</em>.<br>
{wait 3s}<br>
→<br>
</aside>
</section>
<!-- Introducing borrowing. -->
<section>
<dl>
<dt>Borrow</dt>
<dd class="fragment">
<span class="rust">Access</span> to a value <em>without</em> the obligation to destroy that value when it
goes out of scope.
</dd>
</dl>
<aside class="notes">
But you don't have to give away ownership of a value to grant access to it. An owner can <em>lend</em> a
value out;<br>
→<br>
or, reversing the viewpoint, another binding can <em>borrow</em> a value from its owner. Borrowing is
different from ownership because it conveys capability to access, or even modify, a value but does not
bestow the responsibility for destroying that value.<br>
{wait 2s}<br>
→<br>
</aside>
</section>
<!-- Demonstrate borrowing. -->
<section data-auto-animate="borrowing">
<div>
<pre style="font-size: medium"><code class="language-rust" data-trim data-line-numbers data-noescape>
struct Wrapped<T>(
T // Owner of some `T`
);
enum Either<'a, 'b, A, B> {
A(&'a A), // Immutable borrow of some `A` with lifetime 'a
B(&'b B), // Immutable borrow of some `B` with lifetime 'b
}
fn main() {
let w = Wrapped(5); // Owner of `Wrapped(5)`
let mut a = Either::A(&w); // Mutable owner of `Either`; `w` immutably borrowed
f(&mut a); // `a` mutably borrowed, updated by call
} // `a` & `w` destroyed by end of block
fn f<'a, A>(
e: &mut Either<'a, 'a, A, A> // Mutable borrow of some `Either`
) {
*e = match e {
Either::A(a) => // `a` owns borrow of `A`
Either::B(a), // `e` becomes owner of new `Either`; `a` moved
Either::B(b) => // `a` owns borrow of `A`
Either::A(b) // `e` becomes owner of new `Either`; `b` moved
}
}
</code></pre>
<p>Borrowing</p>
</div>
<aside class="notes">
Naturally, there are some important rules governing borrowed values, otherwise we wouldn't need a borrow
checker!<br>
→<br>
</aside>
</section>
<!-- Rules of borrowing. -->
<section data-auto-animate="borrowing">
<div style="width: 50%; float: left">
<pre style="font-size: medium"><code class="language-rust" data-trim data-line-numbers data-noescape>
struct Wrapped<T>(
T // Owner of some `T`
);
enum Either<'a, 'b, A, B> {
A(&'a A), // Immutable borrow of some `A` with lifetime 'a
B(&'b B), // Immutable borrow of some `B` with lifetime 'b
}
fn main() {
let w = Wrapped(5); // Owner of `Wrapped(5)`
let mut a = Either::A(&w); // Mutable owner of `Either`; `w` immutably borrowed
f(&mut a); // `a` mutably borrowed, updated by call
} // `a` & `w` destroyed by end of block
fn f<'a, A>(
e: &mut Either<'a, 'a, A, A> // Mutable borrow of some `Either`
) {
*e = match e {
Either::A(a) => // `a` owns borrow of `A`
Either::B(a), // `e` becomes owner of new `Either`; `a` moved
Either::B(b) => // `a` owns borrow of `A`
Either::A(b) // `e` becomes owner of new `Either`; `b` moved
}
}
</code></pre>
<p>Borrowing</p>
</div>
<div style="margin-left: 50%">
<p>Rules of borrowing:</p>
<ul>
<li>
<em class="rust">Either</em> there may be <span class="rust">one</span> mutable borrow</li>
<li class="fragment">
<em class="rust">Or</em> there may be <span class="rust">zero</span> or <span class="rust">many</span>
immutable borrows
</li>
<li class="fragment">
References must refer to <span class="rust">live</span> values, i.e., <em>no dangling references</em>
</li>
</ul>
</div>
<aside class="notes">
Firstly, there can be only one mutable borrower of some referenced value. So long as a mutable borrow
exists, no other borrows can exist at all. And while the mutable borrow exists, even the owner cannot modify
the underlying value. If you think of this in physical object terms, it makes perfect sense — how can you
scribble in the margins of a book that you've lent out to a friend?<br>
→<br>
Secondly, so long as no mutable borrower exists, there can be many immutable borrowers of some referenced
value. The physical analogy isn't straightforward here, because I usually can't lend the same book to each
of my friends. Something to do with conservation of mass, I don't know. But fortunately, there's a good
analogy from concurrent programming: read/write locks!<br>
→<br>
Lastly, references cannot outlive their owners. If they could, then they could become invalid by pointing to
freed (and potentially reused) memory. But the borrow checker statically ensures that all borrows occur
within the lexical scope of the owner. In other words, borrows have to go out of scope before or
simultaneously with the owner. And just like that, Rust prohibits <em>dangling references</em> by
construction.<br>
→<br>
</aside>
</section>
<!-- Cheating the borrow checker: try #1. -->
<section
data-auto-animate="naive-borrow"
data-background-color="#AD1210"
>
<div class="row">
<div class="column" style="width: 50%; height: auto">
<div>
<pre style="font-size: medium"><code class="language-rust" data-trim data-line-numbers data-noescape>
fn owner_dropped_while_borrowed() {
let outer_borrow: &i32;
{
let inner_borrow: &i32;
let owner: i32 = 10;
inner_borrow = &owner;
outer_borrow = inner_borrow;
}
println!("heh, heh = {}", outer_borrow);
}
</code></pre>
<p>Borrower, schmorrower</p>
</div>
</div>
<img
class="column"
src="assets/Snidely%20Whiplash.svg"
alt="Snidely Whiplash, trying to break Rust"
style="width: 50%; height: auto">
</div>
<aside class="notes">
But does it? Does it really? What happens if I do something sneaky, like this? Here, I've nested two scopes.
Inside the inner scope is the hapless and doomed owner of the value `10`, as well as the creatively named
<code>inner_borrow</code> of <code>owner</code>. But in the outer scope is the villainous
<code>outer_borrow</code>, which tries to borrow <code>owner</code> indirectly through the unsuspecting
<code>inner_borrow</code>. Since <code>owner</code> goes out of scope on line 8 and
<code>outer_borrow</code> survives until line 10, <code>outer_borrow</code> should become a dangling
reference after line 8.<br>
→<br>
</aside>
</section>
<!-- Cheating the borrow checker: fail #1. -->
<section
data-auto-animate="naive-borrow"
data-background-gradient="linear-gradient(to bottom, #FF474C, #8B47AC)"
>
<pre style="font-size: medium"><code class="language-rust" data-trim data-line-numbers data-noescape>
fn owner_dropped_while_borrowed() {
let outer_borrow: &i32;
{
let inner_borrow: &i32;
let owner: i32 = 10;
inner_borrow = &owner;
outer_borrow = inner_borrow;
}
println!("heh, heh = {}", outer_borrow);
}
</code></pre>
<pre class="console" style="font-size: medium">
<span class="command">➜ cargo build</span>
<span class="command">Compiling</span> rust-presentation-2023-11-09 v0.1.0 (/naive-borrow)
<span class="error">error[E0597]</span>: `owner` does not live long enough
<span class="advice">--></span> naive-borrow/src/main.rs:6:18
<span class="advice">|</span>
<span class="advice">5 |</span> let owner: i32 = 10;
<span class="advice">| ----- binding `owner` declared here</span>
<span class="advice">6 |</span> inner_borrow = &owner;
<span class="advice">|</span> <span class="error">^^^^^^ borrowed value does not live long enough</span>
<span class="advice">7 |</span> outer_borrow = inner_borrow;
<span class="advice">8 |</span> }
<span class="advice">| - `owner` dropped here while still borrowed</span>
<span class="advice">9 |</span> println!("heh, heh = {}", outer_borrow);
<span class="advice">| ------------ borrow later used here</span>
For more information about this error, try `rustc --explain E0597`.
<span class="error">error</span>: could not compile `naive-borrow` (bin "naive-borrow") due to previous error
</pre>
<p>Curses, foiled again!</p>
<aside class="notes">
Is Rust going to stand for that? Nah, not really. The borrow checker noticed that owner didn't live long
enough to accommodate the <code>outer_borrow</code>, so it forbade the assignment outright, even though it
tried using <code>inner_borrow</code> as a patsy.<br>
→<br>
</aside>
</section>
<!-- Cheating the borrow checker: try #2. -->
<section
data-auto-animate="sneaky-borrow"
data-background-color="#AD1210"
>
<div class="row">
<div class="column" style="width: 50%; height: auto">
<div>
<pre style="font-size: medium" data-id="code">
<code class="language-rust" data-trim data-line-numbers data-noescape>
fn assign_through_borrow(
a: &mut &i32,
b: &mut &i32
) {
*b = *a;
}
fn owner_dropped_while_borrowed() {
let outer_owner = 10;
let mut outer_borrow = &outer_owner;
{
let inner_owner = 10;
let mut inner_borrow = &inner_owner;
assign_through_borrow(
&mut inner_borrow,
&mut outer_borrow
);
}
println!("heh, heh = {}", outer_borrow);
}
</code>
</pre>
<p>Borrower, schmorrower</p>
</div>
</div>
<img
class="column"
src="assets/Snidely%20Whiplash.svg"
alt="Snidely Whiplash, trying to break Rust"
style="width: 50%; height: auto">
</div>
<aside class="notes">
But maybe we can get even more creative, by using an intermediate function call to disguise our perfidy.
Here, we've introduced two owners, <code>outer_owner</code> and <code>inner_owner</code>, and initialized
matching borrows, <code>outer_borrow</code> and <code>inner_borrow</code>. Nothing suspicious so far.
<code>assign_to_borrow</code> looks innocent enough, too — it just does an assignment whose effect is
visible in the caller. But the actual call of <code>assign_to_borrow</code> is super sketch — it mutably
borrows <code>inner_borrow</code> and <code>outer_borrow</code> so that the callee can make
<code>outer_borrow</code> point to <code>inner_owner</code>. Muahaha, dangling reference created! Suck it,
Rust!<br>
→<br>
</aside>
</section>
<!-- Cheating the borrow checker: fail #2. -->
<section
data-auto-animate="sneaky-borrow"
data-background-gradient="linear-gradient(to bottom, #FF474C, #8B47AC)"
>
<pre style="font-size: medium" data-id="code">
<code class="language-rust" data-trim data-line-numbers data-noescape>
fn assign_through_borrow(
a: &mut &i32,
b: &mut &i32
) {
*b = *a;
}
</code>
</pre>
<pre class="console" style="font-size: medium">
<span class="command">➜ cargo</span> build
<span class="command">Compiling</span> sneaky-borrow v0.1.0 (/sneaky-borrow)
<span class="error">error</span>: lifetime may not live long enough
<span class="advice">--></span> sneaky-borrow/src/main.rs:5:2
<span class="advice">|</span>
<span class="advice">2 |</span> a: &mut &i32,
<span class="advice">| - let's call the lifetime of this reference `'1`</span>
<span class="advice">3 |</span> b: &mut &i32
<span class="advice">| - let's call the lifetime of this reference `'2`</span>
<span class="advice">4 |</span> ) {
<span class="advice">5 |</span> *b = *a;
<span class="advice">|</span> <span class="error">^^^^^^^ assignment requires that `'1` must outlive `'2`</span>
<span class="advice">|</span>
<span class="help">help</span>: consider introducing a named lifetime parameter
<span class="advice">|</span>
<span class="advice">1</span> <span class="note">~</span> fn assign_through_borrow<<span class="note">'a</span>>(
<span class="advice">2</span> <span class="note">~</span> a: &mut &<span class="note">'a</span> i32,
<span class="advice">3</span> <span class="note">~</span> b: &mut &<span class="note">'a</span> i32
<span class="advice">|</span>
<span class="error">error</span>: could not compile `sneaky-borrow` (bin "sneaky-borrow") due to previous error
</pre>
<p>Curses, foiled again!</p>
<aside class="notes">
Wait, what's this? Rust won't compile <code>assign_to_borrow</code>! Curses, foiled again! But how did it
know?<br>
There's more to a borrow than its referent. There's also its <em>lifetime</em>. In other words, how long the
borrow points to a live owner. In <em>any language</em>, a reference must not outlive its referent's owner,
because that's how you get dangling references, yo. But in Rust, the compiler enables — nay, <em>forces</em>
— you to get it right. The borrow checker statically tracks the lifetime of every borrow, and it does this
by implicitly or explicitly attaching a lifetime through a built-in property. The property is expressed as a
generic type parameter of the enclosing context; in this case, the function
<code>assign_to_borrow</code>.<br>
Now we can unpack the compiler's error message. The compiler forbade the redirection of <code>b</code>'s
content to <code>a</code>'s content because it assumed that their lifetimes were unrelated. And in a vacuum,
what else _could_ it assume? Most assumptions would be wrong in most circumstances, so Rust makes the most
general possible assumption, thereby forcing us to clarify our intentions.<br>
→<br>
</aside>
</section>
<!-- Cheating the borrow checker: try #3. -->
<section
data-auto-animate="sneaky-borrow"
data-background-color="#AD1210"
>
<div class="row">
<div class="column" style="width: 50%; height: auto">
<div>
<pre style="font-size: medium" data-id="code">
<code class="language-rust" data-trim data-line-numbers data-noescape>
fn annotated_assign_through_borrow<
'a: 'b,
'b
>(
a: &mut &'a i32,
b: &mut &'b i32,
) {
*b = *a;
}
fn owner_dropped_while_borrowed() {
let outer_owner = 10;
let mut outer_borrow = &outer_owner;
{
let inner_owner = 10;
let mut inner_borrow = &inner_owner;
annotated_assign_through_borrow(
&mut inner_borrow,
&mut outer_borrow
);
}
println!("heh, heh = {}", outer_borrow);
}
</code>
</pre>
<p>Borrower, schmorrower</p>
</div>
</div>
<img
class="column"
src="assets/Snidely%20Whiplash.svg"
alt="Snidely Whiplash, trying to break Rust"
style="width: 50%; height: auto">
</div>
<aside class="notes">
Okay, let's make one last ditch effort to achieve villainy, because I don't know why. We're going to add two
lifetime parameters to <code>assign_to_borrow</code>, one for each formal parameter. We'll name the
lifetimes after the formal parameters themselves, out of convenience rather than syntactic necessity, and
we're going to use a colon to say that <code>'a</code> outlives <code>'b</code>. That guarantees locally
that we can perform the assignment.<br>
→<br>
</aside>
</section>
<!-- Cheating the borrow checker: fail #3. -->
<section
data-auto-animate="sneaky-borrow"
data-background-gradient="linear-gradient(to bottom, #FF474C, #8B47AC)"
>
<pre style="font-size: medium" data-id="code">
<code class="language-rust" data-trim data-line-numbers data-noescape>
fn owner_dropped_while_borrowed() {
let outer_owner = 10;
let mut outer_borrow = &outer_owner;
{
let inner_owner = 10;
let mut inner_borrow = &inner_owner;
annotated_assign_through_borrow(
&mut inner_borrow,
&mut outer_borrow
);
}
println!("heh, heh = {}", outer_borrow);
}
</code>
</pre>
<pre class="console" style="font-size: medium">
<span class="command">➜ cargo</span> build
<span class="command">Compiling</span> sneaky-borrow-with-lifetime v0.1.0 (/sneaky-borrow-with-lifetime)
<span class="error">error[E0597]</span>: `inner_owner` does not live long enough
<span class="advice">--></span> sneaky-borrow-with-lifetime/src/main.rs:13:26
<span class="advice">|</span>
<span class="advice">12 |</span> let inner_owner = 10;
<span class="advice">| ----------- binding `inner_owner` declared here</span>
<span class="advice">13 |</span> let mut inner_borrow = &inner_owner;
<span class="advice">|</span> <span class="error">^^^^^^^^^^^^ borrowed value does not live long enough</span>
<span class="advice">...</span>
<span class="advice">18 |</span> }
<span class="advice">| - `inner_owner` dropped here while still borrowed</span>
<span class="advice">19 |</span> println!("heh, heh = {}", outer_borrow);
<span class="advice">| ------------ borrow later used here</span>
For more information about this error, try `rustc --explain E0597`.
<span class="error">error</span>: could not compile `sneaky-borrow-with-lifetime` (bin "sneaky-borrow-with-lifetime")
due to previous error
</pre>
<p>Curses, foiled again!</p>
<aside class="notes">
You may already be able to guess why this won't work. And there it is, we're straight back to the original
"problem". Now that we've told Rust the relationship between the lifetimes, it throws them right back in our
face to defeat our insidious attempt to create a dangling reference. So … yeah. Rust really does prevent
dangling references by construction. Pretty sweet, yeah?<br>
But if the story ended here, then it would be an incomplete story. What we've seen is impressive, but it
doesn't cover the gamut of memory access patterns. What about heap-resident values? What about shared
ownership? What about cycles? More generally, what about situations where it's much harder to decide when a
value should be destroyed? Well, Rust provides several smart pointer types that flesh out its memory safety
story.<br>
→<br>
</aside>
</section>
<!-- Box. -->
<section>
<pre><code class="language-rust" data-trim data-noescape>
// Excerpted from standard library.
pub struct Box<
// Any type, even if size is statically unknown
T: ?Sized,
// To support "placement new"
A: Allocator = Global
>(Unique<T>, A); // `Unique` means "sole owner"
</code></pre>
<img
src="assets/Box.svg"
alt="Graph"
style="width: 33%; height: auto"/>
<p><code class="rust">Box</code></p>
<aside class="notes">
The simplest is <code>Box</code>, which simply designates a value that lives on the heap. By default, Rust
allocates all values on the stack, but <code>Box</code> and other smart pointers maintain their referents on
the heap. <code>Box</code> is usually the right choice for types whose instances vary in size.
<code>Box</code> is generic over two type parameters: <code>T</code>, which represents the type on the heap;
and <code>A</code>, the type of the allocator responsible for managing that heap. Usually you only care
about <code>T</code>, but <code>A</code> is available for so-called "placement new" situations, à la C++. In
the vast majority of cases where you don't care, you don't have to mention A at all, and Rust will sensibly
default it to the same type as the global allocator. There's no special magic here — like C++ and TypeScript
and unlike Java, Kotlin, Scala, C#, and others, Rust supports default bindings for generic parameters. A
<code>Box</code> is the sole owner of its content, so the content lives exactly as long as the
<code>Box</code> does. When the <code>Box</code> goes out of scope, it and its contents are both
destroyed.<br>
→<br>
</aside>
</section>
<!-- Introduction to shared ownership. -->
<section>
<img
src="assets/Graph%20no%20Rc.svg"
alt="Graph"
style="width: 33%; height: auto"/>
<p>Who owns <code class="rust">E</code>?</p>
<aside class="notes">
The semantics of single ownership is nice and clean, but what if you have shared ownership? The classical
example is a graph structure, where some nodes are held by multiple edges. Ownership of the nodes
conceptually belongs to the whole graph, but usually the graph is a network of related objects, not a single
object where ownership can be centralized. A natural enough approach is to share ownership of a node among
its incoming edges, but how do we achieve this?<br>
→<br>
</aside>
</section>
<!-- Rc. -->
<section>
<pre><code class="language-rust" data-trim data-noescape>
// Simplified from standard library.
pub struct RcInner<T: ?Sized> {
// Interiorly mutable strong count
strong: Cell<usize>,
// Interiorly mutable weak count (for cycle breaking)
weak: Cell<usize>,
// The shared value
value: T
}
pub struct Rc<T: ?Sized> {
// The shared value, plus reference counts
inner: Box<RcInner<T>>
}
</code></pre>
<p>Simplified <code class="rust">Rc</code></p>
<aside class="notes">
<code>Rc</code> to the rescue. Rc stands for <em>reference counter</em>. <code>Rc</code> is really just a
thin wrapper for a private kind of <code>Box</code> that places both the referent and the reference counter
on the heap. This reference counter is incremented whenever the <code>Rc</code> is cloned, and decremented
whenever the <code>Rc</code> goes out of scope. When the reference count goes to zero, the referent is
destroyed. And because no <code>Rc</code> is outstanding, by definition, there are no dangling references to
the defunct referent.<br>
→<br>
</aside>
</section>
<!-- Graph with Rc. -->
<section>
<pre><code class="language-rust" data-trim data-noescape>
pub struct GraphNode<T> {
// The payload
value: T,
// The vector of successors