-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprint.html
787 lines (740 loc) · 51.5 KB
/
print.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
<!DOCTYPE HTML>
<html lang="en" class="sidebar-visible no-js light">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>Tutorial</title>
<meta name="robots" content="noindex" />
<!-- Custom HTML head -->
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff" />
<link rel="icon" href="favicon.svg">
<link rel="shortcut icon" href="favicon.png">
<link rel="stylesheet" href="css/variables.css">
<link rel="stylesheet" href="css/general.css">
<link rel="stylesheet" href="css/chrome.css">
<link rel="stylesheet" href="css/print.css" media="print">
<!-- Fonts -->
<link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
<link rel="stylesheet" href="fonts/fonts.css">
<!-- Highlight.js Stylesheets -->
<link rel="stylesheet" href="highlight.css">
<link rel="stylesheet" href="tomorrow-night.css">
<link rel="stylesheet" href="ayu-highlight.css">
<!-- Custom theme stylesheets -->
<link rel="stylesheet" href="visualization.css">
</head>
<body>
<!-- Provide site root to javascript -->
<script type="text/javascript">
var path_to_root = "";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
</script>
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script type="text/javascript">
try {
var theme = localStorage.getItem('mdbook-theme');
var sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') && theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
</script>
<!-- Set the theme before any content is loaded, prevents flash -->
<script type="text/javascript">
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('no-js')
html.classList.remove('light')
html.classList.add(theme);
html.classList.add('js');
</script>
<!-- Hide / unhide sidebar before it is displayed -->
<script type="text/javascript">
var html = document.querySelector('html');
var sidebar = 'hidden';
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
}
html.classList.remove('sidebar-visible');
html.classList.add("sidebar-" + sidebar);
</script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
<div class="sidebar-scrollbox">
<ol class="chapter"><li class="chapter-item expanded "><a href="motivation.html"><strong aria-hidden="true">1.</strong> Motivation</a></li><li class="chapter-item expanded "><a href="rust-basics.html"><strong aria-hidden="true">2.</strong> Rust Basics</a></li><li class="chapter-item expanded "><a href="ownership.html"><strong aria-hidden="true">3.</strong> Ownership</a></li><li class="chapter-item expanded "><a href="borrowing.html"><strong aria-hidden="true">4.</strong> Borrowing</a></li><li class="chapter-item expanded "><a href="vectors.html"><strong aria-hidden="true">5.</strong> Vectors</a></li><li class="chapter-item expanded "><a href="structs.html"><strong aria-hidden="true">6.</strong> Optional: Structures</a></li><li class="chapter-item expanded "><a href="additional_resources.html"><strong aria-hidden="true">7.</strong> Additional Resources</a></li></ol>
</div>
<div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
</nav>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky bordered">
<div class="left-buttons">
<button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i>
</button>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
<i class="fa fa-paint-brush"></i>
</button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
</ul>
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
<i class="fa fa-search"></i>
</button>
</div>
<h1 class="menu-title">Tutorial</h1>
<div class="right-buttons">
<a href="print.html" title="Print this book" aria-label="Print this book">
<i id="print-button" class="fa fa-print"></i>
</a>
</div>
</div>
<div id="search-wrapper" class="hidden">
<form id="searchbar-outer" class="searchbar-outer">
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
</form>
<div id="searchresults-outer" class="searchresults-outer hidden">
<div id="searchresults-header" class="searchresults-header"></div>
<ul id="searchresults">
</ul>
</div>
</div>
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
<script type="text/javascript">
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
</script>
<div id="content" class="content">
<main>
<h1 id="a-visual-introduction-to-rust"><a class="header" href="#a-visual-introduction-to-rust">A Visual Introduction to Rust</a></h1>
<p>This is a short introduction to the Rust programming language, intended for
programmers with some C or C++ experience. </p>
<p>The tutorial makes use of an interactive visualization system for Rust code
being developed by FP Lab. You should read this tutorial before completing
the remaining questions, Q2 and Q3. </p>
<h1 id="motivation"><a class="header" href="#motivation">Motivation</a></h1>
<p>C and C++ are popular languages for low-level systems programming because they
give programmers direct control over memory allocation and deallocation.
However, these languages are not <em>memory safe</em>. Programs can crash or exhibit
security vulnerabilities due to memory-related bugs, such as use-after-free
bugs. Programs can also have memory leaks, which occur when memory is not freed
even when it is no longer needed.</p>
<p>Most other popular languages are memory safe, but this comes at the cost of
run-time performance: they rely on a run-time garbage collector to automatically
free memory when it is no longer being used. The overhead of garbage collection
can be significant for performance critical tasks.</p>
<p>Rust is designed to be the best of both worlds: it is memory safe without the
need for a garbage collector. Instead, it relies on a compile-time ownership and
borrowing system to automatically determine when memory can be freed. </p>
<p>The trade-off is that Rust's ownership and borrowing system can be difficult to
learn. The purpose of this tutorial is to help you learn Rust's ownership and
borrowing system visually.</p>
<p>For example, this tutorial will help you understand code like the following.
Hover over the different components of the visualization to see explanations.
Don't worry yet about what is going on in detail—these concepts will be
explained in this tutorial.</p>
<div class="flex-container vis_block" style="position:relative; margin-left:-75px; margin-right:-75px; display: flex;">
<object type="image/svg+xml" class="hatra2 code_panel" data="assets/code_examples/hatra2/vis_code.svg"></object>
<object type="image/svg+xml" class="hatra2 tl_panel" data="assets/code_examples/hatra2/vis_timeline.svg" style="width: auto;" onmouseenter="helpers('hatra2')"></object>
</div>
<h2 id="research-disclosure"><a class="header" href="#research-disclosure">Research Disclosure</a></h2>
<p>Your exercise answers and logs of your interactions with this tool might be used
for research purposes. All data used for research purposes will be anonymized:
your identity will not be connected to this data. If you wish to opt out, you
can contact the instructor ([email protected]) at any time up to seven days after
final grades have been issued. Opting out has no impact on your grade. </p>
<p>Click the next button on the right of the page to continue.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="rust-basics"><a class="header" href="#rust-basics">Rust Basics</a></h1>
<h2 id="main-function"><a class="header" href="#main-function">Main Function</a></h2>
<p>In every Rust program, the <code>main</code> function executes first:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
// code here will run first
}
</code></pre></pre>
<h2 id="variables"><a class="header" href="#variables">Variables</a></h2>
<p>In Rust, we use <code>let</code> bindings to introduce variables. Variables are <em>immutable</em>
or <em>mutable</em>.</p>
<h3 id="immutable-variables"><a class="header" href="#immutable-variables">Immutable Variables</a></h3>
<p>By default, variables are <em>immutable</em> in Rust. This means that once a value is
bound to the variable, the binding cannot be changed. We use <code>let</code> bindings to
introduce immutable variables as follows:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let x = 5;
}
</code></pre></pre>
<p>In this example, we introduce a variable <code>x</code> of type <code>i32</code> (a 32-bit signed
integer type) and bind the value <code>5</code> to it. </p>
<p>You cannot assign to an immutable variable. So the following example causes a
compiler error:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let x = 5;
x = 6; // ERROR: cannot assign twice to immutable variable x
}
</code></pre></pre>
<h3 id="mutable-variables"><a class="header" href="#mutable-variables">Mutable Variables</a></h3>
<p>If you want to be able to assign to a variable, it must be marked as <em>mutable</em>
with <code>let mut</code>:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let mut x = 5;
x = 6; //OK
}
</code></pre></pre>
<h2 id="copies"><a class="header" href="#copies">Copies</a></h2>
<p>For simple types like integers, binding and assignment creates a copy.
For example, we can bind the value <code>5</code> to <code>x</code> and then bind <code>y</code> with a copy of <code>x</code>:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let x = 5;
let y = x;
}
</code></pre></pre>
<p>Copying occurs only for simple types like <code>i32</code> and other types that
have been marked as copyable (they implement the <code>Copy</code> trait -- we will not
discuss traits here).
We will discuss how more interesting data
structures that are not copyable behave differently in later sections
of the tutorial.</p>
<h2 id="functions"><a class="header" href="#functions">Functions</a></h2>
<p>Besides <code>main</code>, we can define additional functions. In the following example, we
define a function called <code>plus_one</code> which takes an <code>i32</code> as input and returns an
<code>i32</code> value that is one more than the input:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let six = plus_one(5);
}
fn plus_one(x: i32) -> i32 {
x + 1
}
</code></pre></pre>
<p>Notice how there is no explicit return. In Rust, if the last expression in the
function body does not end in a semicolon, it is the return value. (Rust also
has a <code>return</code> keyword, but we do not use it here.)</p>
<h2 id="printing-to-the-terminal"><a class="header" href="#printing-to-the-terminal">Printing to the Terminal</a></h2>
<p>In Rust, we can print to the terminal using <code>println!</code>:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
println!("Hello, world!")
}
</code></pre></pre>
<p>This code prints <code>Hello, world!</code> to the terminal, followed by a newline
character.</p>
<p>We can also use curly brackets in the input string of <code>println!</code> as a
placeholder for subsequent arguments:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let x = 1;
let y = 2;
println!("x = {} and y = {}", x, y);
}
</code></pre></pre>
<p>This prints <code>x = 1 and y = 2</code>.</p>
<p>Note that the <code>!</code> at the end of <code>println!</code> indicates that it is a <em>macro</em>, not a
function. It behaves slightly differently from normal functions, but you do not
need to worry about the details here. </p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="ownership"><a class="header" href="#ownership">Ownership</a></h1>
<p>In the previous section, we considered only simple values, like integers.
However, in real-world Rust programs, we work with more complex data structures that
allocate resources on the heap. When we allocate resources, we need a strategy
for de-allocating these resources. Most programming languages use one of two
strategies:</p>
<ol>
<li>
<p>Manual Deallocation (C, C++): The programmer is responsible for explicitly
deallocating memory, e.g. using <code>free</code> in C or <code>delete</code> in C++. This is
performant but can result in critical memory safety issues such as use-after-free bugs,
double-free bugs, and memory leaks. These can cause crashes, memory corruption, and
security vulnerabilities. In fact, about 70% of security bugs in major software
products like Windows and Chrome are due to memory safety issues.</p>
</li>
<li>
<p>Garbage Collection (OCaml, Java, Python, etc.): The programmer does not have to
explicitly deallocate memory. Instead, a <em>garbage collector</em> frees (deallocates)
memory by doing a dynamic analysis that detects when no further references to the data remain
live.
This prevents memory
safety bugs. However, a garbage collector can incur sometimes substantial run-time
performance overhead.</p>
</li>
</ol>
<p>Rust uses a third strategy—a static (i.e. compile-time) ownership system.
Because this is a purely compile-time mechanism, it achieves memory safety
without the performance overhead of garbage collection!</p>
<p>The key idea is that each resource in memory has a unique <em>owner</em>,
which controls access to that resource. When the
owner's lifetime ends (it "dies"), e.g. by going out of scope,
the resource is deallocated (in Rust,
we say that the resource is <em>dropped</em>.)</p>
<h2 id="heap-allocated-strings"><a class="header" href="#heap-allocated-strings">Heap-Allocated Strings</a></h2>
<p>For example, heap-allocated strings, of type <code>String</code>, are managed by Rust's ownership system.
Consider the following example, which constructs a heap-allocated string and
prints it out.</p>
<div class="flex-container vis_block" style="position:relative; margin-left:-75px; margin-right:-75px; display: flex;">
<object type="image/svg+xml" class="string_from_print code_panel" data="assets/code_examples/string_from_print/vis_code.svg"></object>
<object type="image/svg+xml" class="string_from_print tl_panel" data="assets/code_examples/string_from_print/vis_timeline.svg" style="width: auto;" onmouseenter="helpers('string_from_print')"></object>
</div>
<p>This code prints <code>hello</code>.</p>
<p>The <code>String::from</code> function allocates a <code>String</code> on the heap. The <code>String</code> is
initialized from a provided string literal (string literals themselves have a
more primitive type, <code>&str</code>, but that detail is not important here.) Ownership
of this string resource is <em>moved</em> to the variable <code>s</code> (of type <code>String</code>) when
<code>String::from</code> returns on Line 2.</p>
<p>The <code>println!</code> macro does not cause a change in ownership (we say more about
<code>println!</code> later.)</p>
<p>At the end of the <code>main</code> function, the variable <code>s</code> goes out of scope. It has
ownership of the string resource, so Rust will <em>drop</em>, i.e. deallocate, the
resource at this point. We do not need an explicit <code>free</code> or <code>delete</code> like we
would in C or C++, nor is there any run-time garbage collection overhead. </p>
<p>Hover over the lines and arrows in the visualization next to the code example
above to see a description of the events that occur on each line of code.</p>
<h2 id="moves"><a class="header" href="#moves">Moves</a></h2>
<p>In the example above, we saw that ownership of the heap-allocated string moved
to the caller when <code>String::from</code> returned. This is one of several ways in which
ownership of a resource can move. We will now consider each situation in
more detail. </p>
<h3 id="binding"><a class="header" href="#binding">Binding</a></h3>
<p>Ownership can be moved when initializing a binding with a variable. </p>
<p>In the following example, we define a variable <code>x</code> that owns a <code>String</code>
resource. Then, we define another variable, <code>y</code>, initialized with <code>x</code>. This
causes ownership of the string resource to be moved from <code>x</code> to <code>y</code>. Note that
this behavior is different than than the copying behavior for simple types like
integers that we discussed in the previous section. </p>
<div class="flex-container vis_block" style="position:relative; margin-left:-75px; margin-right:-75px; display: flex;">
<object type="image/svg+xml" class="string_from_move_print code_panel" data="assets/code_examples/string_from_move_print/vis_code.svg"></object>
<object type="image/svg+xml" class="string_from_move_print tl_panel" data="assets/code_examples/string_from_move_print/vis_timeline.svg" style="width: auto;" onmouseenter="helpers('string_from_move_print')"></object>
</div>
<p>This code prints <code>hello</code>.</p>
<p>At the end of the function, both <code>x</code> and <code>y</code> go out of scope (their lifetimes
have ended). <code>x</code> does not own a resource anymore, so nothing special happens.
<code>y</code> does own a resource, so its resource is dropped. Hover over the
visualization to see how this works.</p>
<p>Each resource must have a unique owner, so <code>x</code> will no longer own the <code>String</code>
resource after it is moved to <code>y</code>. This means that access to the resource
through <code>x</code> is no longer possible. Think of it like handing a resource to
another person: you no longer have access to it once it has moved. For
example, the following generates a compiler error:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let x = String::from("hello");
let y = x;
println!("{}", x) // ERROR: x does not own a resource
}
</code></pre></pre>
<p>The compiler error actually says <code>borrow of moved value: x</code> (we will discuss what
<em>borrow</em> means in the next section.)</p>
<p>If we move to a variable that has a different scope, e.g. due to curly braces,
then you can see by
hovering over the visualization that the resource is dropped at the end of <code>y</code>'s
scope rather than at the end of <code>x</code>'s scope.</p>
<div class="flex-container vis_block" style="position:relative; margin-left:-75px; margin-right:-75px; display: flex;">
<object type="image/svg+xml" class="move_different_scope code_panel" data="assets/code_examples/move_different_scope/vis_code.svg"></object>
<object type="image/svg+xml" class="move_different_scope tl_panel" data="assets/code_examples/move_different_scope/vis_timeline.svg" style="width: auto;" onmouseenter="helpers('move_different_scope')"></object>
</div>
<p>This code prints <code>hello</code> on one line and <code>Hello, world!</code> on the next.</p>
<h3 id="assignment"><a class="header" href="#assignment">Assignment</a></h3>
<p>As with binding, ownership can be moved by assignment to a mutable variable,
e.g. <code>y</code> in the following example.</p>
<div class="flex-container vis_block" style="position:relative; margin-left:-75px; margin-right:-75px; display: flex;">
<object type="image/svg+xml" class="move_assignment code_panel" data="assets/code_examples/move_assignment/vis_code.svg"></object>
<object type="image/svg+xml" class="move_assignment tl_panel" data="assets/code_examples/move_assignment/vis_timeline.svg" style="width: auto;" onmouseenter="helpers('move_assignment')"></object>
</div>
<p>When <code>y</code> acquires ownership over <code>x</code>'s resource on Line 4, the resource it
previously acquired (on Line 3) no longer has an owner, so it is dropped.</p>
<h3 id="function-call"><a class="header" href="#function-call">Function Call</a></h3>
<p>Ownership is moved into a function when it is called with a resource argument.
As an example,
below we see that ownership of the string resource in <code>main</code> is moved from <code>s</code>
to the <code>takes_ownership</code> function. Consequently, when <code>s</code> goes out of scope at
the end of <code>main</code>, there is no owned string resource to be dropped.</p>
<div class="flex-container vis_block" style="position:relative; margin-left:-75px; margin-right:-75px; display: flex;">
<object type="image/svg+xml" class="func_take_ownership code_panel" data="assets/code_examples/func_take_ownership/vis_code.svg"></object>
<object type="image/svg+xml" class="func_take_ownership tl_panel" data="assets/code_examples/func_take_ownership/vis_timeline.svg" style="width: auto;" onmouseenter="helpers('func_take_ownership')"></object>
</div>
<p>This code prints <code>hello</code>.</p>
<p>From the perspective of <code>takes_ownership</code>, it can be assumed that the argument
variable <code>some_string</code> will receive ownership of a <code>String</code> resource from the
caller (each time it is called). The argument variable <code>some_string</code> goes out of
scope at the end of the function, so the resource that it owns is dropped at
that point.</p>
<h3 id="return"><a class="header" href="#return">Return</a></h3>
<p>Finally, ownership can be returned from a function. </p>
<p>In the following example, <code>f</code> allocates a <code>String</code> and returns it to the
caller. Ownership is moved from <code>x</code> to the caller, so there is no owned resource
to be dropped at the end of <code>f</code>. Instead, the resource is dropped when the new
owner, <code>s</code>, goes out of scope at the end of <code>main</code>. (If the <code>String</code> were
dropped at the end of <code>f</code>, there would be a use-after-free bug in <code>main</code> on Line
9!)</p>
<div class="flex-container vis_block" style="position:relative; margin-left:-75px; margin-right:-75px; display: flex;">
<object type="image/svg+xml" class="move_func_return code_panel" data="assets/code_examples/move_func_return/vis_code.svg"></object>
<object type="image/svg+xml" class="move_func_return tl_panel" data="assets/code_examples/move_func_return/vis_timeline.svg" style="width: auto;" onmouseenter="helpers('move_func_return')"></object>
</div>
<p>This code prints <code>hello</code>.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="borrowing"><a class="header" href="#borrowing">Borrowing</a></h1>
<p>In the previous section, we learned that each resource has a unique owner.
Ownership can be moved—for example, into a function.</p>
<p>In many situations, however, we do not want to permanently move a resource into
a function. Instead, we want to retain ownership but allow the function to temporarily
access the resource while it executes.</p>
<p>We could accomplish this by having each function agree to return resources of this
sort. For
example, <code>take_and_return_ownership</code> below takes ownership of a string
resource and returns ownership of that exact same resource. The caller, <code>main</code>,
assigns the returned resource to the same variable, <code>s</code>. </p>
<div class="flex-container vis_block" style="position:relative; margin-left:-75px; margin-right:-75px; display: flex;">
<object type="image/svg+xml" class="func_take_return_ownership code_panel" data="assets/code_examples/func_take_return_ownership/vis_code.svg"></object>
<object type="image/svg+xml" class="func_take_return_ownership tl_panel" data="assets/code_examples/func_take_return_ownership/vis_timeline.svg" style="width: auto;" onmouseenter="helpers('func_take_return_ownership')"></object>
</div>
<p>This code prints <code>hello</code> twice.</p>
<p>The type of
<code>take_and_return_ownership</code> does not guarantee that the returned resource is the
same as the provided resource. Instead, the programmer has to trust that it returns
the same resource.</p>
<p>As code becomes more complex, this pattern of returning all of the provided
resources explicitly becomes both syntactically and semantically unwieldy.</p>
<p>Fortunately, Rust offers a powerful solution: passing in arguments via a
reference. Taking a reference does <em>not</em> change the owner of a resource.
Instead, the reference simply <em>borrows</em> access to the resource temporarily.
Rust's <em>borrow checker</em> requires that references to resources do not outlive
their owner, to avoid the possibility of there being references to resources
that the ownership system has decided can be dropped.</p>
<p>There are two kinds of borrows in Rust, <em>immutable borrows</em> and <em>mutable
borrows</em>. These differ in how much access to the resource they provide. </p>
<h2 id="immutable-borrows"><a class="header" href="#immutable-borrows">Immutable Borrows</a></h2>
<p>In the following example, we define a function, <code>f</code>, that takes an <em>immutable
reference</em> to a <code>String</code>, which has type <code>&String</code>, as input. It then de-references
the immutable reference, written <code>*s</code>, in order to print it.</p>
<p>When the <code>main</code> function calls <code>f</code>, it must provide a reference to a <code>String</code> as
an argument. Here, we do so by taking a reference to the let-bound variable <code>x</code>
on Line 3, written <code>&x</code>. Taking a reference does <strong>not</strong> cause a change in
ownership, so <code>x</code> still owns the string resource in the remainder of <code>main</code>
and it can, for example, print <code>x</code> on Line 4. The resource will be dropped when
<code>x</code> goes out of scope at the end of <code>main</code> as we discussed previously. Because <code>f</code>
takes a reference, it is only <em>borrowing</em> access to the resource that the
reference points to. It does not need to explicitly return the resource because
it does not own it. Rust knows that the borrow does not outlive the owner
because the borrow is no longer accessible after <code>f</code> returns.</p>
<div class="flex-container vis_block" style="position:relative; margin-left:-75px; margin-right:-75px; display: flex;">
<object type="image/svg+xml" class="immutable_borrow code_panel" data="assets/code_examples/immutable_borrow/vis_code.svg"></object>
<object type="image/svg+xml" class="immutable_borrow tl_panel" data="assets/code_examples/immutable_borrow/vis_timeline.svg" style="width: auto;" onmouseenter="helpers('immutable_borrow')"></object>
</div>
<p>This code prints <code>hello</code> twice.</p>
<p>Note: you do not actually need to dereference <code>s</code> to pass it to <code>println!</code> in Rust:
it is a macro, so it will automatically dereference or borrow as needed
to ensure that a move is not needed. Indeed, Rust does a lot of implicit
borrowing and dereferencing to make its syntax simple, as we will see in other examples
below.</p>
<p>Methods of the <code>String</code> type, like <code>len</code> for computing the length, typically
take their arguments by reference. You can call a method explicitly with a
reference, e.g. <code>String::len(&s)</code>. As shorthand, you can use dot notation to
call a method, e.g. <code>s.len()</code>. This implicitly takes a reference to <code>s</code>. </p>
<div class="flex-container vis_block" style="position:relative; margin-left:-75px; margin-right:-75px; display: flex;">
<object type="image/svg+xml" class="immutable_borrow_method_call code_panel" data="assets/code_examples/immutable_borrow_method_call/vis_code.svg"></object>
<object type="image/svg+xml" class="immutable_borrow_method_call tl_panel" data="assets/code_examples/immutable_borrow_method_call/vis_timeline.svg" style="width: auto;" onmouseenter="helpers('immutable_borrow_method_call')"></object>
</div>
<p>This code prints <code>len1 = 5 = len2 = 5</code>.</p>
<p>You can keep multiple immutable borrows live at the same time, e.g. <code>y</code> and <code>z</code>
in the following example are both live as shown in the visualization. For this
reason, immutable borrows are also sometimes called shared borrows: each
immutable reference shares access to the resource with the owner and with any
other immutable references that might be live.</p>
<div class="flex-container vis_block" style="position:relative; margin-left:-75px; margin-right:-75px; display: flex;">
<object type="image/svg+xml" class="multiple_immutable_borrow code_panel" data="assets/code_examples/multiple_immutable_borrow/vis_code.svg"></object>
<object type="image/svg+xml" class="multiple_immutable_borrow tl_panel" data="assets/code_examples/multiple_immutable_borrow/vis_timeline.svg" style="width: auto;" onmouseenter="helpers('multiple_immutable_borrow')"></object>
</div>
<p>This code prints <code>hello and hello</code>.</p>
<p>Ownership of a resource cannot be moved while it is borrowed. For example, the
following is erroneous:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let s = String::from("hello");
let x = &s;
let s2 = s; // ERROR: cannot move s while a borrow is live
println!("{}", String::len(x));
}
</code></pre></pre>
<p>The compiler error here is: <code>cannot move out of s because it is borrowed</code>.</p>
<h2 id="mutable-borrows"><a class="header" href="#mutable-borrows">Mutable Borrows</a></h2>
<p>Unlike immutable borrows, Rust's mutable borrows allow you to mutate the
borrowed resource. In the example below, we push (copy) the contents of a <code>String</code> <code>s2</code>
to the end of the heap-allocated <code>String</code> <code>s1</code> twice, first by explictly calling
the <code>String::push_str</code> method, and then using the equivalent shorthand method
call syntax. In both cases, the method takes a <em>mutable reference</em> to <code>s1</code>,
written explicitly <code>&mut s1</code>.</p>
<div class="flex-container vis_block" style="position:relative; margin-left:-75px; margin-right:-75px; display: flex;">
<object type="image/svg+xml" class="mutable_borrow_method_call code_panel" data="assets/code_examples/mutable_borrow_method_call/vis_code.svg"></object>
<object type="image/svg+xml" class="mutable_borrow_method_call tl_panel" data="assets/code_examples/mutable_borrow_method_call/vis_timeline.svg" style="width: auto;" onmouseenter="helpers('mutable_borrow_method_call')"></object>
</div>
<p>This code prints <code>Hello, world, world</code>.</p>
<p>Code that does a lot of mutation is notoriously difficult to reason about, so in
Rust, mutation is much more carefully controlled than in other imperative
languages.</p>
<p>First, you can only take a mutable borrow from a mutable variable, i.e. one
bound using <code>let mut</code> like <code>s1</code> in the example above. Immutability is the
default in Rust because it is considered easier to reason about.</p>
<p>Second, mutable borrows are unique—you cannot take a borrow, mutable or
immutable, if any mutable borrow is live. This means that you can be certain
that no other code will be mutating a resource when you have mutably borrowed it.
For this reason, mutable borrows are also sometimes called <em>unique borrows</em>.</p>
<p>For example, the following code is erroneous because a mutable borrow, <code>y</code>, is
live.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let mut x = String::from("hello");
let y = &mut x;
f(&x); // ERROR: y is still live
String::push_str(y, ", world");
}
fn f(x : &String) {
println!("{}", x);
}
</code></pre></pre>
<p>The compiler error here is: <code>cannot borrow x as immutable because it is also borrowed as mutable</code>.</p>
<p>The following code is erroneous for the same reason.</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let mut x = String::from("Hello");
let y = &mut x;
let z = &mut x; // ERROR: y is still live
String::push_str(y, ", world");
String::push_str(z, ", friend");
println!("{}", x);
}
</code></pre></pre>
<p>The compiler error here is: <code>cannot borrow x as mutable more than once at a time</code>.</p>
<h3 id="optional-threading-in-rust"><a class="header" href="#optional-threading-in-rust">Optional: Threading in Rust</a></h3>
<p>In the example above, the two calls to <code>push_str</code> are sequenced. However, if we
wanted to execute them concurrently, we could do so by spawning a thread as
follows. Here, <code>|| { e }</code> is Rust's notation for an anonymous function taking
unit input.</p>
<pre><pre class="playground"><code class="language-rust">use std::thread;
fn main() {
let mut x = String::from("Hello");
let y = &mut x;
let z = &mut x; // NOT OK: y is still live
thread::spawn(|| { String::push_str(y, ", world"); });
String::push_str(z, ", friend");
println!("{}", x);
}
</code></pre></pre>
<p>If the borrow checker did not stop us, this program would have a race
condition—it could print either <code>Hello, world, friend</code> or <code>Hello, friend, world</code>
depending on the interleaving of the main thread and the newly spawned thread.
By tightly controlling mutation, Rust prevents races mediated by shared mutable state.
(The topic of parallelism and concurrency in Rust will be explored further in A9!)</p>
<h2 id="non-lexical-lifetimes"><a class="header" href="#non-lexical-lifetimes">Non-Lexical Lifetimes</a></h2>
<p>Above, we use the phrase "live borrow". A borrow is <em>live</em> if it is in scope and
there remain future uses of the borrow. A borrow dies as soon it is no longer
needed. So the following code works, even though there are two mutable borrows
in the same scope:</p>
<div class="flex-container vis_block" style="position:relative; margin-left:-75px; margin-right:-75px; display: flex;">
<object type="image/svg+xml" class="nll_lexical_scope_different code_panel" data="assets/code_examples/nll_lexical_scope_different/vis_code.svg"></object>
<object type="image/svg+xml" class="nll_lexical_scope_different tl_panel" data="assets/code_examples/nll_lexical_scope_different/vis_timeline.svg" style="width: auto;" onmouseenter="helpers('nll_lexical_scope_different')"></object>
</div>
<p>This code prints <code>Hello, world, world!!</code>.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="vectors-in-rust"><a class="header" href="#vectors-in-rust">Vectors in Rust</a></h1>
<p>The previous sections cover everything you need to know about ownership and borrowing in Rust! This section introduces another interesting data structure: vectors.</p>
<p>Like with other languages, the Rust standard library contains many useful
<em>collection</em> types. One of the most useful and common ones are <em>vectors</em>, which
have type <code>Vec<T></code>, where <code>T</code> is the type the that vector holds.</p>
<p>Vectors are heap-allocated, mutable collections that store multiple values of
the same type contiguously in memory. In many ways, they are similar C++
<code>vector</code>s and serve similar purposes.</p>
<p>Vectors are implemented with <em>generics</em>, which allow them to hold any type.
For example, we can have <code>Vec<i32></code> and <code>Vec<String></code> which are the types of
<code>i32</code> vectors and <code>String</code> vectors, respectively. Vectors can hold any
<code>struct</code> or <code>enum</code> type as well. </p>
<h2 id="creating-a-vector"><a class="header" href="#creating-a-vector">Creating A Vector</a></h2>
<h3 id="empty-vectors"><a class="header" href="#empty-vectors">Empty Vectors</a></h3>
<p>To make a new empty vector, we can use the <code>Vec::new()</code> function as follows:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let v: Vec<i32> = Vec::new();
}
</code></pre></pre>
<p>Here, <code>Vec::new()</code> creates an empty vector of <code>i32</code>s and moves ownership to <code>v</code>.
Note that we included a type annotation to <code>v</code>. This is necessary here because
otherwise, Rust won't know which type of vector to create. </p>
<h3 id="creating-vectors-from-initial-values"><a class="header" href="#creating-vectors-from-initial-values">Creating Vectors from Initial Values</a></h3>
<p>We can also create new vectors with initial values using the <code>vec!</code> macro:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let v = vec![1, 2 ,3];
}
</code></pre></pre>
<p>Here, we create a new <code>Vec<i32></code> containing the values <code>1</code>, <code>2</code>, and <code>3</code> in
that order. Note that in this case, we did not need to include a type annotation
for <code>v</code>. This is because we are creating the vector with initial values of a
specific type, so Rust can figure out the type of <code>v</code> in this case.</p>
<h2 id="reading-elements-of-vectors"><a class="header" href="#reading-elements-of-vectors">Reading Elements of Vectors</a></h2>
<h3 id="accessing-an-element-at-a-particular-index"><a class="header" href="#accessing-an-element-at-a-particular-index">Accessing an Element at a Particular Index</a></h3>
<p>We can use the indexing syntax or the <code>get()</code> method to get the value at a
particular index of the vector:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let v = vec![1, 2, 3];
let third: &i32 = &v[2];
println!("The third element is {}", third);
match v.get(2) {
Some(third) => println!("The third element is {}", third),
None => println!("There is no third element."),
}
}
</code></pre></pre>
<p>Here, we use both ways of getting a particular element. The first way is using
the indexing syntax (square brackets), which gives us an immutable reference to
the element. The second way is using the <code>get()</code> method, which returns an
<code>Option</code> type. </p>
<p>With the indexing syntax, if we performed an out-of-bounds access in the vector,
the program would <em>panic</em> (i.e. cause an unrecoverable error.) With the <code>get()</code>
method, an out-of-bounds access would result in the method returning <code>None</code>.
With the <code>get()</code> method, we can handle out-of-bounds accesses gracefully rather
than causing the program to crash. </p>
<h3 id="iterating-over-elements"><a class="header" href="#iterating-over-elements">Iterating over Elements</a></h3>
<p>We can iterate over elements in a vector with a <code>for</code> loop to read the values:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let v = vec![1, 2, 3];
for i in &v {
println!("{}", i);
}
}
</code></pre></pre>
<p>Here, we simply read the values of the vector and print them to the terminal.
Note that the <code>for</code> loop is immutably borrowing <code>v</code>, as shown by the <code>&v</code>.</p>
<h2 id="mutating-vectors"><a class="header" href="#mutating-vectors">Mutating Vectors</a></h2>
<h3 id="push"><a class="header" href="#push">Push</a></h3>
<p>We can add elements to the back of a vector using the <code>push()</code> method:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let mut v = Vec::new();
v.push(1);
v.push(2);
v.push(3);
}
</code></pre></pre>
<p>This creates an empty vector and adds the values <code>1</code>, <code>2</code>, and <code>3</code> to the back
of the vector in that order. In this case, we did not need a type annotation
because the type is inferred from the values we pushed to it. Note that we made
<code>v</code> a mutable variable here. If we didn't, the borrow checker would not allow
us to make calls to <code>push()</code>.</p>
<h3 id="writing-elements-at-a-particular-index"><a class="header" href="#writing-elements-at-a-particular-index">Writing Elements at a Particular Index</a></h3>
<p>We can also write to elements at a particular index in a similar way to how
we read elements at a particular index. We can use the indexing syntax or the
<code>get_mut()</code> method:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let mut v = vec![1, 2, 3];
let second: &mut i32 = &mut v[1];
*second = 3;
match v.get_mut(2) {
Some(third) => *third = 9,
None => println!("There is no third element."),
}
}
</code></pre></pre>
<p>Here, we use the indexing syntax to get a mutable reference to the second
element and change its value to <code>3</code>. We then use the <code>get_mut()</code> method to get
a mutable reference to the third element and change its value to <code>9</code>.</p>
<p>As with the example for reading elements at a particular index, an out-of-bounds
access with the indexing sytanx can cause a <code>panic</code> while an out-of-bounds
access with the <code>get_mut()</code> method returns <code>None</code>.</p>
<h3 id="iterating-over-elements-1"><a class="header" href="#iterating-over-elements-1">Iterating Over Elements</a></h3>
<p>We can iterate over elements in a vector with a <code>for</code> loop to mutate the values:</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
let mut v = vec![1, 2, 3];
for i in &mut v {
*i = *i + 1
}
}
</code></pre></pre>
<p>Here, we add <code>1</code> to each of the values in the vector. Note that the <code>for</code> loop
is mutably borrowing <code>v</code>, as shown by the <code>&mut v</code>.</p>
<div style="break-before: page; page-break-before: always;"></div><h3 id="optional-structs-in-rust"><a class="header" href="#optional-structs-in-rust">Optional: Structs in Rust</a></h3>
<h4 id="creating-a-struct"><a class="header" href="#creating-a-struct">Creating a struct</a></h4>
<p>To define a struct, we enter the keyword <code>struct</code> and name the entire struct. A struct’s name should describe the significance of the pieces of data being grouped together. Then, inside curly brackets, we define the names and types of the pieces of data, which we call <em>fields</em>. Here is an example showing a struct that stores information about a user account.</p>
<pre><pre class="playground"><code class="language-rust">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
<span class="boring">}
</span></code></pre></pre>
<p>We create an instance by stating the name of the struct and then add curly brackets containing <code>key: value</code> pairs, where the keys are the names of the fields and the values are the data we want to store in those fields. Then we can use dot field to obtain the value in a struct.</p>
<pre><pre class="playground"><code class="language-rust">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span> let mut user1 = User {
email: String::from("[email protected]"),
username: String::from("someusername123"),
active: true,
sign_in_count: 1,
};
user1.email = String::from("[email protected]");
<span class="boring">}
</span></code></pre></pre>
<p>Each fields in the struct can be referenced independently. Here's an example of defining a struct, generating an instance of it, letting it interact with functions and referencing field <code>r.h</code>.</p>
<div class="flex-container vis_block" style="position:relative; margin-left:-75px; margin-right:-75px; display: flex;">
<object type="image/svg+xml" class="struct_rect code_panel" data="assets/code_examples/struct_rect/vis_code.svg"></object>
<object type="image/svg+xml" class="struct_rect tl_panel" data="assets/code_examples/struct_rect/vis_timeline.svg" style="width: auto;" onmouseenter="helpers('struct_rect')"></object>
</div>
<h4 id="calling-a-method-in-a-struct"><a class="header" href="#calling-a-method-in-a-struct">Calling a method in a struct</a></h4>
<p>Struct can also include methods whose definition is given in the <code>impl</code> of it. When calling a method or a variable from a struct, we use <code>object.something()</code>or <code> (&object).something()</code>, which are the same. No matter it is a <code>&, &mut, *</code>or nothing, always use <code>.</code> and not need to use <code>-></code> because Rust will automatically adds in <code>&, &mut, *</code> so <code>object</code> matches the signature of the method. </p>
<div class="flex-container vis_block" style="position:relative; margin-left:-75px; margin-right:-75px; display: flex;">
<object type="image/svg+xml" class="struct_rect2 code_panel" data="assets/code_examples/struct_rect2/vis_code.svg"></object>
<object type="image/svg+xml" class="struct_rect2 tl_panel" data="assets/code_examples/struct_rect2/vis_timeline.svg" style="width: auto;" onmouseenter="helpers('struct_rect2')"></object>
</div>
<h4 id="ownership-of-struct-data"><a class="header" href="#ownership-of-struct-data">Ownership of struct data</a></h4>
<p>When the instance of the struct owns all its fields, i.e. no reference or pointer in the struct, the ownership is basically the same with data outside of a struct. It's also possible for fields of a struct to own resources. Here's an example of the cases where one of the field <code>y</code> owns a <code>string</code> resouce.</p>
<div class="flex-container vis_block" style="position:relative; margin-left:-75px; margin-right:-75px; display: flex;">
<object type="image/svg+xml" class="struct_string code_panel" data="assets/code_examples/struct_string/vis_code.svg"></object>
<object type="image/svg+xml" class="struct_string tl_panel" data="assets/code_examples/struct_string/vis_timeline.svg" style="width: auto;" onmouseenter="helpers('struct_string')"></object>
</div>
<p>When the any of the data members is not owned by the struct, it needs lexical lifetime specified to allow the struct owning a reference of a data resouce. This will ensure that the resource referenced will have the same lifetime as the struct as long as they share the same lexical lifetime label.</p>
<p>Here is an example of using lifetime annotations <code><'a></code> in struct definitions to allow reference of string <code>&p</code> in a <code>struct Excerpt</code>.</p>
<div class="flex-container vis_block" style="position:relative; margin-left:-75px; margin-right:-75px; display: flex;">
<object type="image/svg+xml" class="struct_lifetime code_panel" data="assets/code_examples/struct_lifetime/vis_code.svg"></object>
<object type="image/svg+xml" class="struct_lifetime tl_panel" data="assets/code_examples/struct_lifetime/vis_timeline.svg" style="width: auto;" onmouseenter="helpers('struct_lifetime')"></object>
</div>
<div style="break-before: page; page-break-before: always;"></div><h1 id="additional-resources"><a class="header" href="#additional-resources">Additional Resources</a></h1>
<p>This tutorial introduced you to the basics of Rust and its ownership and
borrowing system. If you are interested in diving deeper into Rust, here are
some helpful resources:</p>
<ul>
<li><a href="https://doc.rust-lang.org/book/">The Rust Programming Language (a.k.a. "the book")</a>: An overview of Rust from first principles</li>
<li><a href="https://github.com/rust-lang/rustlings/">Rustlings</a>: Small exercises in Rust</li>
<li><a href="https://doc.rust-lang.org/stable/rust-by-example/">Rust By Example</a>: Introduces Rust concepts by through examples, as the name suggests</li>
<li><a href="https://www.rust-lang.org/learn">Learn Rust</a>: Contains links to many different Rust learning resources including the ones above</li>
</ul>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<div style="clear: both"></div>
</nav>
</div>
</div>
<nav class="nav-wide-wrapper" aria-label="Page navigation">
</nav>
</div>
<script type="text/javascript">
window.playground_copyable = true;
</script>
<script src="elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
<script src="mark.min.js" type="text/javascript" charset="utf-8"></script>
<script src="searcher.js" type="text/javascript" charset="utf-8"></script>
<script src="clipboard.min.js" type="text/javascript" charset="utf-8"></script>
<script src="highlight.js" type="text/javascript" charset="utf-8"></script>
<script src="book.js" type="text/javascript" charset="utf-8"></script>
<!-- Custom JS scripts -->
<script type="text/javascript" src="helpers.js"></script>
<script type="text/javascript">
window.addEventListener('load', function() {
window.setTimeout(window.print, 100);
});
</script>
</body>
</html>