summaryrefslogtreecommitdiff
path: root/presentation.md
blob: f1881eacc94aaa9ffe55349ca9f14d2802ee85cf (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
title: Rust in brief
class: animation-fade
layout: true

.bottom-bar[
{{title}}
]

---

count: false

# Leader slide

- Press 'b' to toggle 'blackout mode'
- Press 'p' to toggle 'presenter mode'
- Press 'c' to create a clone of this window which will keep up
- Press left/right to move around slides
- The next slide is where the presentation begins

???

This is where presenter notes appear

---

class: impact

# {{title}}

## Daniel Silverstone <br /><tt>&lt;dsilvers@digital-scurf.org&gt;</tt>

???

- Welcome everyone
- Explain that this is intended to be a brief tour of Rust
- Gauge the audience level?
  - Know what Rust is?
  - Curious / interested in Rust?
  - Have written Rust in the past?
  - Actively maintain code in Rust now?
- My goal is to bring more people into the later categories
- Explain that some of my comparisons, e.g. C++ may be naïve.
- Note that we will only _briefly_ touch on many aspects of Rust and that this
  is not intended to be an in-depth explanation of any single part, just a taster
- Encourage interruptions for questions, but request that people accept sometimes
  I will say "ask me again later please"

---

title: What is Rust?
class: middle

```rust
fn main() {
    println!("Hello world!");
}
```

???

- Rust was conceived by some engineers at Mozilla, in part to replace C++ in
  Firefox.
- C/C++ ish syntax, with some inspiration from ML and Haskell which we'll see
  later in the presentation
- Quite an interesting type system, which, for now, it's sufficient to say is
  not what is thought of as traditional object orientation.
- Rust is a systems programming language

---

title: A systems programming language?

## A 'systems programming' language?

???

- The term 'systems programming language' is bandied around but what does it mean?

--

- Web

???

- Rust can be used to build webassembly modules which can be used in the browser
  to provide complex behaviours such as game engines without relying directly on
  the JavaScript interpreter for everything.

--

- Servers

???

- Rust is used in the server layer (for example hyper)

--

- Command line tools

???

- Rust is an effective language for writing command line tooling in with a
  rich ecosystem of libraries to help with this.

---

count: false

## A 'systems programming' language?

- Web

- Servers

- Command line tools

- Plumbing / Low level

???

- Capable of interacting with low level system calls with ease, Rust is suitable
  for implementing very low level applications and tooling. In theory there's
  no reason an `init` system couldn't be written in Rust

--

- Kernel

???

- While I wouldn't advocate rewriting Linux in Rust, it's possible to write
  loadable modules in Rust, and there are whole operating systems written in
  Rust such as Redox or Tock

--

- Firmware

???

- This is somewhere I see Rust making a huge impact. Its ability to model the
  hardware closely while still providing a number of very interesting static
  guarantees (more later) makes Rust an excellent fit for firmware development.

---

title: Fast, Safe, Easy - Pick Three

## Traditional tensions in systems languages

???

- In languages targetted at a similar set of domains as Rust is, there is
  often a tension between three aspects which we can term 'Fast' 'Safe' and 'Easy.

--

- Fast

???

- One thing which systems programmers usually value very highly is "speed"
  which in this instance we can characterise as "idiomatic code should run
  in as close to the bare minimum cycles as possible"
- If we think about 'Fast' languages we tend to think of C, C++

--

- Safe

???

- Safety in this context means things like 'no use of unallocated memory' and
  no simultaneous mutation of memory in different threads.
- The specific benefit of safe languages is that they free up the programmer to
  think about the work to be done, rather than having to worry about memory etc.
- Safe languages tend to be things like Java, Go, JavaScript
  basically anything with GC.

---

title: Fast, Safe, Easy - Pick Three

## Traditional tensions in systems languages

- Fast

- Safe

- Easy

???

- Programmers like convenient helpers, they like nice helper routines to get their
  common tasks done with minmal programming effort, they like their task of
  instructing the computer to be as easy as possible, to leave their minds free
  to solve the hard problem of _what_ to do, rather than _how_ to do it.
- Easy languages might be those such as Python, maybe even Haskell.

--

- **Pick three**

???

- Rust tries to allow the programmer to pick all three, rather than the tension
  expressed for example in Python where you have safe, easy development at the
  expense of performance; or C++ where you get fast easy-to-write code but you
  have to spend considerable cognitive effort to remain safe.

---

## Traditional tensions in systems languages

- Fast

- Safe

- Easy

- **Pick three**

- How?

???

- Through a combination of LLVM's optimising compiler, Rust's careful construction
  of monomorphised generic functions, (similar to a tracing JIT for JS or Lua),
  and what Rust calls zero-cost-abstractions, idiomatic Rust is pretty much as
  fast as idiomatic C/C++.
- Rust's somewhat unique approach to memory management by enforcing the concepts
  of ownership, safe borrowing, and its extension of that into how it handles
  multiple threads of execution means that Rust's model is fundamentally 'Safe'
  without being garbage collected per-se. Rust advocates sometimes refer to
  this combination of memory safety and multi-threading as 'fearless concurrency'
- Finally, Rust's standard library provides a significant number of useful
  data structures, algorithm implementations, and through Rust's type system, a
  lot of potentially onerous constructs are rendered pretty easy to handle
  making Rust a productive language to work in.

---

## Some useful things to know about Rust

???

- Before we delve into some of Rust's unique properties, let's first look
  at a few useful things to know

--

- Rust is a compiled language

???

- Rust must be compiled before it can be run
- There is not a Rust interpreter
- As a result, I wouldn't generally recommend Rust for rapid prototyping in
  exactly the same way as I might Python

--

- Static typing

???

- Rust is statically typed.
- Every value has exactly one type
- Types include more information than just the data they might contain

---

count: false

## Some useful things to know about Rust

- Rust is a compiled language

- Static typing

- Type inference

???

- Rust supports type inference
- This means you don't _always_ need to name the type of things for the compiler
  to be able to understand your code.
- Type inference can work both to allow you to not name the type of a variable
  binding, but also to specialise a generic function call by constraining its
  return type for you. This is super-useful

--

- Strict non-inference at function boundary definition

???

- Rust requires that you describe the types at function boundaries
- This is less inference than something like Haskell _can_ give you
- But pretty much exactly as much inference as good Haskell programmers rely on
  since it's usually considered good style to give your functions basic type
  signatures even in Haskell

---

## Ownership and borrowing

```cplusplus

void foo() {









}

```

???

- Let's consider a language which smells a bit like C++
- In this we'll play with a simple data structure, a vector, and
  we'll try something a naïve programmer might easily do...

---

count: false

## Ownership and borrowing

```cplusplus

void foo() {
*  std::vector<std::string> stuff;








}

```

???

- First up, let's have a nice shiny new vector on the stack. It'll start
  empty, but be all nice and ready for us to put strings into.

---

count: false

## Ownership and borrowing

```cplusplus

void foo() {
   std::vector<std::string> stuff;

*  stuff.push_back("Hello");






}

```

???

- Now let's put a nice string in

---

count: false

## Ownership and borrowing

```cplusplus

void foo() {
   std::vector<std::string> stuff;

   stuff.push_back("Hello");

*  std::string *first = &stuff[0];




}

```

???

- And then let's get a pointer to it ready to use later.

---

count: false

## Ownership and borrowing

```cplusplus

void foo() {
   std::vector<std::string> stuff;

   stuff.push_back("Hello");

   std::string *first = &stuff[0];

*  stuff.pop();


}

```

???

- Let's pop that off the vector again

---

count: false

## Ownership and borrowing

```cplusplus

void foo() {
   std::vector<std::string> stuff;

   stuff.push_back("Hello");

   std::string *first = &stuff[0];

   stuff.pop();

*  std::cout << first << std::endl;
}

```

???

- Now what do we think happens in this case?
- If we're lucky everything is fine
- But the vector might have reallocated its internal storage, invalidating
  the pointer held in `first`.

---

## Ownership and borrowing in Rust

```rust

fn main() {
    let mut stuff: Vec<String> = Vec::new();

    stuff.push("Hello".to_owned());

    let first: &String = &stuff[0];

    stuff.pop();

    println!("{}", first);
}

```

???

- What will happen here?

---

## Compilation error

<pre style="font-size: 1rem">
<b><span style="color:#F55">error[E0502]</span></b><b>: cannot borrow `stuff` as mutable because it is also borrowed as immutable</b>
 <b><span style="color:#55F">--> </span></b>foo.rs:5:5
  <b><span style="color:#55F">|</span></b>
<b><span style="color:#55F">4</span></b> <b><span style="color:#55F">| </span></b>    let first: &String = &stuff[0];
  <b><span style="color:#55F">| </span></b>                          <b><span style="color:#55F">-----</span></b> <b><span style="color:#55F">immutable borrow occurs here</span></b>
<b><span style="color:#55F">5</span></b> <b><span style="color:#55F">| </span></b>    stuff.pop();
  <b><span style="color:#55F">| </span></b>    <b><span style="color:#F55">^^^^^^^^^^^</span></b> <b><span style="color:#F55">mutable borrow occurs here</span></b>
<b><span style="color:#55F">6</span></b> <b><span style="color:#55F">| </span></b>    println!("{}", first);
  <b><span style="color:#55F">| </span></b>                   <b><span style="color:#55F">-----</span></b> <b><span style="color:#55F">immutable borrow later used here</span></b>

<b><span style="color:#F55">error</span></b><b>: aborting due to previous error</b>

<b>For more information about this error, try `rustc --explain E0502`.</b>
</pre>

???

Rust simply won't let us do this.

---

## Passing ownership

```rust
fn take(mut foo: Vec<String>) {
    foo.push("Hello".to_owned())
}

fn main() {
    let v = vec![];

    take(v);

    println!("{}", v[0]);
}
```

???

What happens here?

---

## Compilation Error

<pre style="font-size: 1rem">
<b><span style="color:#F55">error[E0382]</span></b><b>: borrow of moved value: `v`</b>
  <b><span style="color:#55F">--> </span></b>foo2.rs:10:20
   <b><span style="color:#55F">|</span></b>
<b><span style="color:#55F">8</span></b>  <b><span style="color:#55F">| </span></b>    take(v);
   <b><span style="color:#55F">| </span></b>         <b><span style="color:#55F">-</span></b> <b><span style="color:#55F">value moved here</span></b>
<b><span style="color:#55F">9</span></b>  <b><span style="color:#55F">| </span></b>
<b><span style="color:#55F">10</span></b> <b><span style="color:#55F">| </span></b>    println!("{}", v[0]);
   <b><span style="color:#55F">| </span></b>                   <b><span style="color:#F55">^</span></b> <b><span style="color:#F55">value borrowed here after move</span></b>
   <b><span style="color:#55F">|</span></b>
   <b><span style="color:#55F">= </span></b><b>note</b>: move occurs because `v` has type `std::vec::Vec<std::string::String>`, which does not implement the `Copy` trait

<b><span style="color:#F55">error</span></b><b>: aborting due to previous error</b>

<b>For more information about this error, try `rustc --explain E0382`.</b>
</pre>

???

- Urgh, yet again it explodes, this time because the vector is moved into the `take`
  function and then destroyed at the end of it.

---

## Borrowing mutably

```rust
*fn take(foo: &mut Vec<String>) {
    foo.push("Hello".to_owned())
}

fn main() {
    let v = vec![];

*   take(&mut v);

    println!("{}", v[0]);
}
```

???

Finally this will work because we've actually told the compiler what we wanted
it to do, and it wasn't crazy.

---

## Further thinking on this topic

- Ownership

???

- Only one part of the code can own a value. Be it on the stack, or in another
  data structure which might be on the stack or the heap.
- Ownership confers the right to mutate
- Also confers the right to hand out mutable or immutable borrows
- Ownership confers the responsibility to destroy when no longer needed

--

- Mutable borrow

???

- If you have a mutable borrow of a value, you have the right to mutate it
- You also have the right to hand that mutable borrow to some other part of
  the code.
- Or to hand out immutable borrows

---

count: false

## Further thinking on this topic

- Ownership

- Mutable borrow

- Immutable borrow (or simply borrow)

???

- If you hold an immutable borrow of a value, you are permitted to read it
  as much as you like, and you can hand immutable borrows to others, but
  you cannot mutate the value
- So long as you hold an immutable borrow, noone can mutate the value, not even
  the owner of the object
- Destruction is a kind of mutation, so immutable borrows cannot outlive the
  lifetime of a value.

---

count: false

## Further thinking on this topic

- Ownership

- Mutable borrow

- Immutable borrow (or simply borrow)

- Lifetimes

???

- Rust extends its traditional type system with the concept of lifetimes.
- Lifetimes are how the compiler (or more precisely the borrow checker) is able
  to do this static analysis and determine the safety or unsafety of your code.
- Lifetimes are a strict heirarchy, that is to say that if a lifetime `b` derives
  from the lifetime `a`, then `a` strictly outlives `b`.
- All values, and both kinds of borrows are simply values, are annotated with
  lifetimes. 99% of the time that's implicit and you never have to see it but
  sometimes in Rust you will see lifetime annotations to help the compiler and
  the reader/user of the code to understand what's necessary

---

## Data types in Rust

???

- Rust has a number of fundamental data types

--

- Primitives - `bool`, `char`, `u8`, `i32`, `usize`

???

- Intrinsics such as booleans, characters, number types.
- Rust supports from 8 to 128 bit integers both signed and unsigned
- Rust supports 32 and 64 bit floating point, and has 16 and 128 bit ones
  in discussion phases

--

- Arrays and Slices - `[u8; 16]`, `[usize]`

???

- Arrays, and slices into arrays, are another fundamental type in Rust.
- Arrays are sized, they have a length as part of their type
- Slices are sized, but at runtime, at compile time the size is unknown

--

- String slices - `str`

???

- In rust, string slices are somewhat interesting, they are a specialisation
  of a slice of `u8` with the added constraint that they represent valid utf8
  data.

---

count: false

## Data types in Rust

- Primitives - `bool`, `char`, `u8`, `i32`, `usize`

- Arrays and Slices - `[u8; 16]`, `[usize]`

- String slices - `str`

- Tuples - `(T1, T2)`, `(T1, T2, T3)`, ...

???

- Tuples are a very simple product type.
- For example a tuple of `i32` and `&str`
- Members of a tuple can be accessed by `.0` `.1` etc.

--

- Structs `struct Foo { ... }`

???

- Structs are similar to tuples, in that they are product types, however their
  fields are named rather than simply indexed.
- Structs can also have methods, associated functions, etc.
- In Rust, the struct is one of the two fundamental kinds of data type which
  you would tend to implement in your code

--

- Enums `enum Foo { ... }`

???

- Enums are slightly different to what you might expect if you're used to C/C++
- Enums are arithmetic data types, which corresponds somewhat more closely to
  a C/C++ struct containing a discriminant and a union of other types.

---

class: impact

## Did you say unions?

???

- Yes, Rust has unions, but just don't use them. No. Don't
- Well, unless you're into scary FFI stuff which needs them.

---

## Structs

```rust
struct Person {
   name: String,
   age: u32,
   weight: u32,
   nicknames: Vec<String>
}
```

???

- Structs have members which have types.
- Structs are, almost invariably, of fixed size
- But they can refer to arbitrarily sized data such as the `name` or `nicknames`
  fields in the example here

---

## Implementation

```rust
impl Person {
    fn new(name: &str, age: u32, weight: u32, nicknames: &[String]) -> Person {
        Person {
            name: name.to_owned(),
            age, weight,
            nicknames: nicknames.iter().cloned().collect(),
        }
    }
}
```

???

- That's a lot to take in, but the fundamental thing to note here is

---

count: false

## Implementation

```rust
*impl Person {
    fn new(name: &str, age: u32, weight: u32, nicknames: &[String]) -> Person {
        Person {
            name: name.to_owned(),
            age, weight,
            nicknames: nicknames.iter().cloned().collect(),
        }
    }
}
```

???

- The `impl` indicates a block of code whose functions are associated with
  the type the implementation is for. In this instance `Person`

---

count: false

## Implementation

```rust
impl Person {
*   fn new(name: &str, age: u32, weight: u32, nicknames: &[String]) -> Person {
        Person {
            name: name.to_owned(),
            age, weight,
            nicknames: nicknames.iter().cloned().collect(),
        }
    }
}
```

???

- The function declaration there results in `Person::new()` our function
  takes a name as a borrowed string, an age and weight by value, and a
  list of nicknames as a borrow of an arbitrarily sized array of strings.
- The syntax at the end there indicates the function returns a `Person` instance

---

count: false

## Implementation

```rust
impl Person {
    fn new(name: &str, age: u32, weight: u32, nicknames: &[String]) -> Person {
*       Person {
*           name: name.to_owned(),
*           age, weight,
*           nicknames: nicknames.iter().cloned().collect(),
*       }
    }
}
```

???

- This syntax is how a struct is instantiated, where the values passed in are
  full expressions or not named identically to the field names, the colon syntax
  is used.
- Don't worry, for now, about the functions you can see there

---

## Enums

```rust
enum ConnectTarget {
    Local,
    AddressPort(IPAddr, u16),
    Hostname(String),
    Voodoo {
        doll: VoodooDoll,
        catalyst: HooDooThingy,
    },
}
```

???

- Enums have variants which come in a number of kinds

---

count: false

## Enums

```rust
enum ConnectTarget {
*   Local,
    AddressPort(IPAddr, u16),
    Hostname(String),
    Voodoo {
        doll: VoodooDoll,
        catalyst: HooDooThingy,
    },
}
```

???

- Simple variants have no associated data, these are the closest to C-type enums

---

count: false

## Enums

```rust
enum ConnectTarget {
    Local,
*   AddressPort(IPAddr, u16),
*   Hostname(String),
    Voodoo {
        doll: VoodooDoll,
        catalyst: HooDooThingy,
    },
}
```

???

- Tuple-kind variants have one or more pieces of associated data, this is where
  enums look a bit more like C unions

---

count: false

## Enums

```rust
enum ConnectTarget {
    Local,
    AddressPort(IPAddr, u16),
    Hostname(String),
*   Voodoo {
*       doll: VoodooDoll,
*       catalyst: HooDooThingy,
*   },
}
```

???

- Struct-kind variants are essentially tuple-kind variants but where the
  associated data has names rather than indices. Fundamentally equivalent
  to tuple variants.

---

## Parametric types

```rust
enum Option<T> {
    None,
    Some(T),
}
```

???

- Rust allows for structs, enums, etc to take type parameters. This means
  that they are generic, similarly to C++ templates, or Haskell higher-kinded-types.
- Rust's `Option<T>` type is similar to Haskell's `Maybe t`

--

## Monomorphisation

- `Option<&str>`
- `HashMap<String, usize>`

???

- When a Rust parametric type is given all its parameters, this defines a
  concrete type. Given that, any methods on that generic type are then
  instantiated for the given set of parameter types and this process is
  called monomorphisation.
- This is one of the reasons Rust code tends to run quickly, there is dedicated
  code for each variant of a parameterised type used in the program, resulting
  in greater potential for optimisation.

---

## Errors

???

- Rust has only two real ways to handle errors or exceptional circumstances

--

- **`panic!()`**

???

- Rust can panic, which means that the current thread of execution is terminated
  the stack is unwound (unless specifically disabled) in an attempt to clean up,
  and then if that was the main thread of execution, the process is terminated.

- The Rust standard library can produce backtraces in this circumstance and that
  can be useful in debugging what is going on.

--

- Return a result

???

- This is, obviously, preferred in general code, rather than panic being called
  at the least provocation, it's better to handle the situation and return.

---

## `panic!()` (via `unwrap()`)

```rust
fn say_age_in_days(input: &str) {
    let age: f32 = input.parse().unwrap();

    println!("You are {} days old!  Wow!", age * 365.25);
}
```

???

- Here, `parse()` returns a possibly-successful possibly-failed
- The `unwrap()` call essentially says "If it failed, panic, otherwise give
  me the result"
- Calling this function with a string which doesn't parse fully as a `f32` will
  result in a panic.

---

## Dealing with the result

```rust
fn say_age_in_days(input: &str) {
    let age = input.parse();

    if age.is_ok() {
        println!("You are {} days old! Wow!", age.unwrap() * 365.25);
    }
}
```

???

- We can guard our use of `unwrap()` with `is_ok()`

---

## Pass it on

```rust
fn say_age_in_days(input: &str) -> Result<(), Error> {
    let age = input.parse();

    if age.is_ok() {
        println!("You are {} days old! Wow!", age.unwrap() * 365.25);
        Ok(())
    } else {
        Err(age.err().unwrap())
    }
}
```

???

- We could rework our function to return a result passing the error along
  to let our caller deal with it. This is good practice in library code
- But that's pretty ugly, can we do better?

---

## Ergonomic passing on of an error

```rust
fn say_age_in_days(input: &str) -> Result<(), Error> {
    println!("You are {} days old! Wow!", age.parse()? * 365.25);
}
```

???

- The questionmark operator there does the error propagation if needed and
  unwraps an ok result for use in the expression.
- Looks like it would get lost, but fairly quickly you learn to spot them
  when you're looking for error escape conditions, and to ignore them
  when you just want to know the flow of the code.
- Added benefit, the questionmark operator also does error type coercion which
  sometimes is necessary.

---

## Rust is not object oriented

- Structs? yes
- Enums? yes
- Inheritance? **no**

???

- Rust is not an object oriented language in the sense you're used to.
- It has structs and enums, which along with methods you could begin to think
  of as objects. Indeed they're generally referred to as instances, and it's
  not unreasonable to think of them as objects.
- But structs or enums are not the equivalent of C++ or Python classes.
- There is no inheritance heirarchy
- Rust does extension by encapsulation

---

## Traits

```rust
trait Edible {
    fn eat(&self);
}

impl Edible for Apple {
    fn eat(&self) {
        println!("Om nom nom!  You crunch an apple.");
    }
}

impl Edible for Soap {
    fn eat(&self) {
        println!("Blech!  You had to eat soap!  Eww!");
    }
}
```

???

- On the face of it, Traits look quite like interfaces or abstract classes
- But traits are interesting because:
  - Traits can be statically dispatched. If you know the type of a value
    as Rust is wont to do, you can know exactly which variant of `eat()` to
    call at compile time
  - Traits can be dynamically dispatched. If you have erased the type of
    a value (through various means) you can dynamically dispatch trait methods
    just like Python or C++ virtual methods.
  - Traits can be used as markers, or to extend other types

---

## Traits

```rust
pub trait Add<RHS = Self> {
    type Output;

    #[must_use]
    fn add(self, rhs: RHS) -> Self::Output;
}


foo = bar + baz;
// becomes:
foo = (bar as Add<RHS=typeof(baz)).add(baz);
// when compiled

```

???

- In Rust, even operators such as addition turn into trait method calls.
- This allows for operator overloading if done carefully
- But still permits static dispatch for efficient code generation

---

## Traits

```rust
for foo in bar {
    // Do something with foo
}
```

???

- Even things like for loops end up using traits...

---

## Traits

```rust
for foo in (bar as IntoIterator).into_iter() {
    // Do something with foo
}
```

???

- The for loop relies on a special trait called `IntoIterator` to do its job
- But we can desugar that further

---

## Traits, and enums, and refutable patterns, oh my!

```rust
{
    let mut _iterator = (bar as IntoIterator).into_iter();
    while let Some(foo) = _iterator.next() {
        // Do something with foo
    }
}
```

???

- And further still

---

## Traits, and enums, and matches, and loops, oh gosh!

```rust
{
    let mut _iterator = (bar as IntoIterator).into_iter();
    loop {
        let foo = match _iterator.next() {
            None => break,
            Some(foo) => foo,
        };
        // Do something with foo
    }
}
```

???

- Here we can see the `match` operator which lets us do pattern matching on
  the types of Rust values. Here we're destructuring the `Option` returned
  by the `next()` method of an iterator, if it returns `None` then we've hit
  the end of the iteraton so we break the loop.

---

## Iterator in more detail

```rust
pub trait Iterator {
    type Item;

    fn next(&mut self) -> Option<Self::Item>;
}
```

???

- Iterators are mutable data structures which every time you call `.next()`
  return the next item as `Some(Item)`.
- When they return `None` the iteration is over and it's considered undefined
  if you call `.next()` again.
- But this is not everything of Iterator

---

## Iterator in more detail

```rust
pub trait Iterator {
    type Item;
    fn next(&mut self) -> Option<Self::Item>;

    fn size_hint(&self) -> (usize, Option<usize>) { ... }
    fn count(self) -> usize { ... }
    fn last(self) -> Option<Self::Item> { ... }
    fn nth(&mut self, n: usize) -> Option<Self::Item> { ... }
    fn step_by(self, step: usize) -> StepBy<Self> { ... }
    fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>
    where
        U: IntoIterator<Item = Self::Item>,
    { ... }
...
```

???

- But there's more

---

## Iterator in more detail

```rust
pub trait Iterator {
...
    fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>
    where
        U: IntoIterator,
    { ... }
    fn map<B, F>(self, f: F) -> Map<Self, F>
    where
        F: FnMut(Self::Item) -> B,
    { ... }
...
```

???

- And more

---

## Iterator in more detail

```rust
pub trait Iterator {
...
    fn for_each<F>(self, f: F)
    where
        F: FnMut(Self::Item),
    { ... }
    fn filter<P>(self, predicate: P) -> Filter<Self, P>
    where
        P: FnMut(&Self::Item) -> bool,
    { ... }
    fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
    where
        F: FnMut(Self::Item) -> Option<B>,
    { ... }
    fn enumerate(self) -> Enumerate<Self> { ... }
...
```

???

- And yet more
- In fact while there's only one required method (`.next()`) which you must
  implement in order to have an iterator, there are over fifty methods which
  the iterator trait provides automatically, given an amazingly ergonomic
  interface and a very convenient set of capabilities to anything iterable.

---

## Iterator use

```rust
let input = stdin.read_to_end();
println!("Sum of first up-to-five valid inputs: {}",
         input.lines()
              .map(|s| s.parse())
              .filter(|v| v.is_ok())
              .map(|v| v.unwrap())
              .take(5)
              .sum());
```

???

- Map lets you run a function over each value returning a new value
- Filter lets you remove elements of an iteration which don't meet a predicate
- Take lets you take up to n elements of the iteration
- sum is implemented for iterators which are numeric and can add them up

---

## Sum of an iterator?

.col-6[

```rust
pub trait Iterator {
...
fn sum<S>(self) -> S
    where
        S: Sum<Self::Item>,
    { ... }
...
}
```

]

.col-6[

```rust
pub trait Sum<A = Self> {
    fn sum<I>(iter: I) -> Self
    where
        I: Iterator<Item = A>;
}
```

].col-12[

```rust
impl Sum for i32 {
    fn sum<I: Iterator<Item=i32>>(iter: I) -> i32 {
        iter.fold(0, Add::add)
    }
}
```

]

???

- The `where` guards allow for traits to define some methods which only exist
  for suitable subsets of implementors of the trait.
- In this instance, the `.sum()` method on the `Iterator` trait only exists
  should there be an implementation of `Sum` for the type which matches the
  type of the iterator's `Item`.

---

## Meta programming, or IOW, macros

- You've seen them already

???

- Rust macros have a postfix exclamation mark, you've seen some already
  such as `println!()`

--

- e.g. `println!()`

???

- Yes, println (and print, and writeln, and write, etc) are all macros. They
  are provided by the standard library

--

- e.g. `include_file!()` or `module_path!()`

???

- Some macros are built into the compiler, such as ones which include files
  for compilation, or turn bits of the code on and off based on configuration
  variables

--

- e.g. `serde::Deserialize`

???

- Some macros are what is called 'proc-macros' or 'procedural macros' and they
  are a special form of Rust library which can be used by the compiler to generate
  code during compilation. This is fairly new and is still being worked on,
  but there are some super-powerful features implemented in this already

---

## Procedural macros?

```rust
#[derive(serde::Deserialize)]
struct DataLump {
    who: String,
    age: Option<u32>,
}

fn main() -> Result<(), Box<std::error::Error>> {
    let input = include_str!("input.json");
    let input: Vec<DataLump> = serde_json::from_str(&input)?;
    for lump in &input {
        println!("{} is {}", lump.who,
                 lump.age.map(|n| format!("{} years old", n))
                     .unwrap_or_else(|| "of unknown age".to_owned()));
    }
    Ok(())
}

```

???

- The Rust compiler can derive some implementations of traits automatically
  for you, such as `Debug` or `PartialEq`/`Eq`
- But you can have complex traits such as `serde::Deserialize` where a there
  is a procedural macro in the library which the compiler can use to generate
  the code for that trait implementation.

_Talk through the code_

---

## The Rust software ecosystem

???

- As much as we might like to think so, programming does not exist in a perfect
  vacuum where all we have is our one code file and our editor.
- Programs, libraries, etc, comprise multiple files, they rely on each other
- They need distribution, aggregation, indexing, etc.
- Programs need formatting, they need documenting, they need checking
- The Rust ecosystem attempts to standardise as much as possible of all this

---

count: false

## The Rust software ecosystem

- `rustc` and `cargo`

???

- At the base of this pyramid is the rust compiler `rustc` which defines at least
  some of how a program goes together. It defines the layout of files
  in the source directory, how modules go together, how things have to be named
  in order that the compiler can find them.
- The fundamental unit of compilation for Rust is called the 'crate' and Cargo
  is the tool which manages them.
- Cargo defines the next level of structure, providing
  a standardised tooling interface and a standard layout for libraries and binaries
  along with tooling to acquire your dependencies, and to build everything and
  rebuild when needed.

---

count: false

## The Rust software ecosystem

- `rustc` and `cargo`
- `crates.io`

???

- Since there needs to be somewhere for all those libraries to live and be discoverable,
  like npm for Node modules, or pypy for Python, Rust has `crates.io`
- It provides an index of all the crates, known to the ecosystem, and at what versions.
- Cargo talks to crates.io to acquire "known good" copies of the crate sources
  which your crate or your dependencies need in order to build

---

count: false

## The Rust software ecosystem

- `rustc` and `cargo`
- `crates.io`
- `clippy`

???

- If you thought a normal C compiler was a bit grumpy
- If you thought a C compiler in `-Wall -pedantic` was a bit rude to you
- If you thought the Rust compiler could get picky with your nits
- You should try `clippy` - it is an additional level of linting which looks
  for antipatterns in your code and teaches you how to do things better or
  in some cases simply correctly.
- For example, it'll encourage you to use `.is_empty()` instead of `.len() == 0`

---

count: false

## The Rust software ecosystem

- `rustc` and `cargo`
- `crates.io`
- `clippy`
- `rustfmt` (and `cargo fmt`)

???

- Consistent code layout reduces cognitive load on consumers of source code
- Rust defines a standard style (though yes it is configurable)
- Tooling exists to help you enforce that style
- Editors often support format-on-save to help you keep to the style

---

count: false

## The Rust software ecosystem

- `rustc` and `cargo`
- `crates.io`
- `clippy`
- `rustfmt` (and `cargo fmt`)
- `rustdoc` (and `cargo doc`)

???

- Code, particularly library code, is not considered complete unless it is
  properly and completely documented. In Rust it's bad if public types,
  methods, fields, etc. lack documentation
- the `rustdoc` format is basically markdown and in fact, similarly to Python,
  code documentation is syntactically part of the language.

---

count: false

## The Rust software ecosystem

- `rustc` and `cargo`
- `crates.io`
- `clippy`
- `rustfmt` (and `cargo fmt`)
- `rustdoc` (and `cargo doc`)
- ... culminating in `https://docs.rs/`

???

- The combination of `crates.io` `cargo` and `rustdoc` culiminates in the
  existence of `docs.rs` which is a site which automatically builds and publishes
  the documentation for every crate on `crates.io`

---

count: false

## The Rust software ecosystem

- `rustc` and `cargo`
- `crates.io`
- `clippy`
- `rustfmt` (and `cargo fmt`)
- `rustdoc` (and `cargo doc`)
- ... culminating in `https://docs.rs/`
- `#[cfg(test)]`, `#[test]`, `tests/*.rs`, and `cargo test`

???

- Code, particularly library code, **DOES NOT WORK** if it's not tested.
- Rust offers many ways to write tests. One really nice way is that you can
  embed code sections into your `rustdoc` and they will be automatically compiled
  and run to ensure that your code documentation works.
- Another way is that the compiler has a test configuration which affects visibility
  of symbols and lets you write test functions which get aggregated and run for you
- Finally `cargo` jumps in and adds a whole layer of integration tests for you
  to use as well, in the `tests/` directory. These get automatically linked to
  your crate for testing, along with test-dependencies managed independently of
  execution dependencies.

---

count: false

## The Rust software ecosystem

- `rustc` and `cargo`
- `crates.io`
- `clippy`
- `rustfmt` (and `cargo fmt`)
- `rustdoc` (and `cargo doc`)
- ... culminating in `https://docs.rs/`
- `#[cfg(test)]`, `#[test]`, `tests/*.rs`, and `cargo test`
- `cargo fix`

???

- Rust compiler errors, warnings, lints, etc often come with recommendation on
  on how to fix them. For example adding or removing references.
- Where those are mechanically applicable, the information is provided to the
  tooling, and `cargo fix` can apply these updates
- This reduces the cognitive load of resolving warnings and lints and therefore
  result in more consistent quality of code across crates.

---

## Installing Rust

???

- Installation is the final piece of the puzzle.
- Typically there are two ways that people get hold of software

--

- Distributions

???

- You get it from your software distribution
- Or...

--

- Download a (source?) tarball/package

???

- You download a tarball/package from the software vendor and build/install it

--

- There _has_ to be something better?

???

- Mmm yes, something better perhaps?

---

class: impact

# `rustup`

???

- The rust community wanted to produce an option which is effective in allowing
  developers to acquire Rust and associated components such as `clippy` or
  `rustfmt` as mentioned before.
- Rustup is the primary official way to get hold of Rust, though by no means the
  only supported method. Debian, Fedora, etc. package `rustc` `cargo` et al.
- Rustup allows you to manage multiple versions of the toolchains, supports
  installing multiple targets to facilitate cross compilation, etc.

---

# Getting Rust

<pre style="font-size: 1.4rem">
$ curl -sSf https://sh.rustup.rs/ > rustup-init.sh
$ ... review rustup-init.sh ...
$ sh rustup-init.sh
...
...
...
Rust is installed now. Great!

To get started you need Cargo's bin directory ($HOME/.cargo/bin) in your PATH
environment variable. Next time you log in this will be done automatically.

To configure your current shell run source $HOME/.cargo/env
</pre>

???

- The recommended way to get Rustup if you simply want to get started is just to
  download it via the `sh.rustup.rs` service. While the website will exhort you
  to just dump that straight into shell, I do recommend a quick check of the
  content of the shell script if you want to be absolutely sure.

---

# Hello World?

<pre style="font-size: 1.5rem">
$ cargo init --bin hello
<b><span style="color:#0A0">     Created</span></b> binary (application) package
$












</pre>

???

First we create the directory and populate it with an initial set of files.

---

count: false

# Hello World?

<pre style="font-size: 1.5rem">
$ cargo init --bin hello
<b><span style="color:#0A0">     Created</span></b> binary (application) package
$ cd hello
$ cat src/main.rs
fn main() {
    println!("Hello, world!");
}
$







</pre>

???

How convenient! Cargo automatically creates our binary as hello world, just so
we can get going

---

count: false

# Hello World?

<pre style="font-size: 1.5rem">
$ cargo init --bin hello
<b><span style="color:#0A0">     Created</span></b> binary (application) package
$ cd hello
$ cat src/main.rs
fn main() {
    println!("Hello, world!");
}
$ cargo run
<b><span style="color:#0A0">   Compiling</span></b> hello v0.1.0 (/tmp/hello)
<b><span style="color:#0A0">    Finished</span></b> dev [unoptimized + debuginfo] target(s) in 0.29s
<b><span style="color:#0A0">     Running</span></b> `target/debug/hello`
Hello, world!
$


</pre>

???

And running the app, cargo will build it and run it, and we see our message.

---

count: false

# Hello World?

<pre style="font-size: 1.5rem">
$ cargo init --bin hello
<b><span style="color:#0A0">     Created</span></b> binary (application) package
$ cd hello
$ cat src/main.rs
fn main() {
    println!("Hello, world!");
}
$ cargo run
<b><span style="color:#0A0">   Compiling</span></b> hello v0.1.0 (/tmp/hello)
<b><span style="color:#0A0">    Finished</span></b> dev [unoptimized + debuginfo] target(s) in 0.29s
<b><span style="color:#0A0">     Running</span></b> `target/debug/hello`
Hello, world!
$ ls
Cargo.lock  Cargo.toml  <b><span style="color:#00A">src</span></b>  <b><span style="color:#00A">target</span></b>
$
</pre>

???

- Finally we can look at what is in the directory. As you can see, there are
  a number of files and directories there.
- `Cargo.toml` describes the metadata for the crate
- `Cargo.lock` is managed by Cargo and ensures that unless you tell Cargo otherwise
  it will always use the same versions of your dependencies. This helps with
  any attempt at reproducibility
- `src` contains your code
- `target` is the build directory, it contains the binaries, intermediate content,
  incremental build caches, etc.

---

# What about a library?

<pre style="font-size: 1.5rem">
$ cargo init --lib mylib
<b><span style="color:#0A0">     Created</span></b> library package
$ cd mylib
$ cat src/lib.rs
#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}
$ cargo build
<b><span style="color:#0A0">   Compiling</span></b> mylib v0.1.0 (/tmp/mylib)
<b><span style="color:#0A0">    Finished</span></b> dev [unoptimized + debuginfo] target(s) in 0.17s
$
</pre>

???

- Libraries come by default with a very basic test to show you how testing works
- We can build the crate in the normal way
- But what about running the tests?

---

# What about a library?

<pre style="font-size: 1.5rem">
$ cargo test
<b><span style="color:#0A0">   Compiling</span></b> mylib v0.1.0 (/tmp/mylib)
<b><span style="color:#0A0">    Finished</span></b> dev [unoptimized + debuginfo] target(s) in 0.34s
<b><span style="color:#0A0">     Running</span></b> target/debug/deps/mylib-b0be8938ca1f0c56

running 1 test
test tests::it_works ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

<b><span style="color:#0A0">   Doc-tests</span></b> mylib

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
$
</pre>

???

- You can see that it ran the tests and the `it_works` test passed as expected
- Also you can see that it tried to run doc tests but didn't find any. As said
  before, doc tests are absolutely first class in Rust and hopefully as you
  develop your library, you'll have plenty of those.

---

## The Rust community

- Reddit `/r/rust`
- Discord `https://discord.gg/rust-lang`
- IRC (Mozilla IRC network, `#rust`, `#rust-beginners` etc.)
- Various Gitter channels (e.g. `#diesel-rs/diesel` for the de-facto database layer)
- The users forum `https://users.rust-lang.org/`
- The internals forum `https://internals.rust-lang.org/`
- All the `https://gitlab.com/rust-lang/` repositories
- All the `https://gitlab.com/rust-lang-nursery/` repositories
- Even `#rust` on Codethink IRC 😁

<!-- -->

### `https://www.rust-lang.org/policies/code-of-conduct`

???

- There are many many places to find news on, and information about Rust
- All governed by a good code of conduct
- Very welcoming environment in my experience. Comparable in quality only with
  the `#haskell` people who were always wonderful when I hung out there.

---

count: false
class: impact

# Any questions?

???

If people want, I can give a brief walk through of some code, perhaps live-code
something, otherwise questions, or I'm done.

---

count: false
class: impact

# One final point

???

Talk about offering opportunity for Rust tutoring, request people contact in
private to express interest, explain that the first group will be experimental
but will offer additional runs later as well.