-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslides.tex
1657 lines (1390 loc) · 48 KB
/
slides.tex
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
\documentclass{beamer}
\usetheme{metropolis}
%\setsansfont[BoldFont={Fira Sans SemiBold}]{Fira Sans Book}
%\setsansfont{Fontin}
%\setsansfont{Gillius ADF No2}
%\setsansfont{Phetsarath OT}
\setsansfont{Source Sans Pro}
\setmonofont{Source Code Pro}
\hypersetup{colorlinks=true,
linkcolor=mRustLightOrange,
menucolor=mRustLightOrange,
pagecolor=mRustLightOrange,
urlcolor=mRustLightOrange}
\usepackage{csquotes}
\usepackage{comment}
\usepackage{xcolor}
\usepackage{minted}
\newfontfamily\codefont{Source Code Pro}
\newcommand\code[1]{\,{\color[HTML]{884400}#1}\,}
\newcommand\source[1]{$\rightarrow$ via #1}
\title{traits \& generics}
\date{\today}
\author{Lukas Prokop}
\institute{RustGraz community\vfill\hfill\includegraphics[height=2cm]{images/rustacean-orig-noshadow.png}}
\begin{document}
\maketitle
% TODO Feedback(David): turn hyperlinks into footnotes
\section{Prologue}
\begin{frame}[fragile]{std::mem::size\_of\_val of union}
\textbf{Last session:} One \code{unsafe} superpower is \enquote{Access fields of unions}. \\
\textbf{Claim:} The size of a union is the size of its largest member.
\begin{minted}{rust}
pub const fn size_of<T>() -> usize
\end{minted}
Returns the size of a type in bytes.
More specifically, this is the offset in bytes between successive elements in an array with that item type including alignment padding. Thus, for any type \mintinline{rust}{T} and length \mintinline{rust}{n}, \mintinline{rust}{[T; n]} has a size of \mintinline{rust}{n * size_of::<T>()}.
In general, the size of a type is not stable across compilations, but specific types such as primitives are.
\source{\href{https://doc.rust-lang.org/std/mem/fn.size_of.html}{rust doc}}
\end{frame}
\begin{frame}[fragile]{std::mem::size\_of\_val of union}
\textbf{Reminder:} a slide from December:
\begin{minted}{rust}
use std::mem;
fn main() {
println!("{}", mem::size_of::<A>());
}
\end{minted}
where \mintinline{rust}{A} is \mintinline{rust}{u8} (1), \mintinline{rust}{u32} (4), \mintinline{rust}{f64} (8), \mintinline{rust}{&u8} (8), \mintinline{rust}{String} (24), \mintinline{rust}{&str} (16), \mintinline{rust}{Vec<u8>} (24) or \mintinline{rust}{&[char]} (16).
\end{frame}
\begin{frame}[fragile]{std::mem::size\_of\_val of union}
\textbf{Size of} \mintinline{rust}{#[repr(C)]} \textbf{ items}
The C representation for items has a defined layout. With this layout, the size of items is also stable as long as all fields have a stable size.
\textbf{Size of Unions}
The size of a union is the size of its largest field.
Unlike C, zero sized unions are not rounded up to one byte in size.
\source{\href{https://doc.rust-lang.org/std/mem/fn.size_of.html\#size-of-reprc-items}{rust doc}}
\end{frame}
\begin{frame}[fragile]{std::mem::size\_of\_val of union}
\begin{minted}{rust}
use std::mem::size_of;
#[repr(C)]
union Ambiguous {
my_int: u32,
addr: *const u32,
}
fn main() {
println!("{}", size_of::<Ambiguous>());
// ⇒ 8
}
\end{minted}
\end{frame}
\begin{frame}[fragile]{alignment of struct}
\begin{minted}{rust}
pub const fn align_of<T>() -> usize
\end{minted}
Returns the ABI-required minimum alignment of a type.
Every reference to a value of the type T must be a multiple of this number.
This is the alignment used for struct fields. It may be smaller than the preferred alignment.
\source{\href{https://doc.rust-lang.org/std/mem/fn.size_of.html}{rust doc}}
\end{frame}
\begin{frame}[fragile]{alignment of struct}
\textbf{Size of Structs}
For structs, the size is determined by the following algorithm.
For each field in the struct ordered by declaration order:
\begin{enumerate}
\item Add the size of the field.
\item Round up the current size to the nearest multiple of the next field's alignment.
\end{enumerate}
Finally, round the size of the struct to the nearest multiple of its alignment. The alignment of the struct is usually the largest alignment of all its fields; this can be changed with the use of \code{repr(align(N))}.
Unlike C, zero sized structs are not rounded up to one byte in size.
\end{frame}
\begin{frame}[fragile]{alignment of struct}
\begin{minted}{rust}
use std::mem::{size_of,align_of};
fn main() {
println!("{} ⇒ {}", size_of::<i32>(),
align_of::<i32>()); // 4 ⇒ 4
println!("{} ⇒ {}", size_of::<u8>(),
align_of::<u8>()); // 1 ⇒ 1
println!("{} ⇒ {}", size_of::<*mut i32>(),
align_of::<*mut i32>()); // 8 ⇒ 8
println!("{} ⇒ {}", size_of::<usize>(),
align_of::<usize>()); // 8 ⇒ 8
println!("{} ⇒ {}", size_of::<char>(),
align_of::<char>()); // 4 ⇒ 4
}
\end{minted}
\end{frame}
\begin{frame}[fragile]{alignment of struct}
\begin{minted}{rust}
struct Data {
a: i32,
b: u8,
c: *mut i32,
d: usize,
e: char,
}
struct SomeU8 {
a: u8,
b: u8,
}
\end{minted}
\end{frame}
\begin{frame}[fragile]{alignment of struct}
\begin{minted}{rust}
struct SomeI32 {
a: i32,
b: i32,
}
fn main() {
println!("{} ⇒ {}", size_of::<Data>(),
align_of::<Data>()); // 32 ⇒ 8
println!("{} ⇒ {}", size_of::<SomeU8>(),
align_of::<SomeU8>()); // 2 ⇒ 1
println!("{} ⇒ {}", size_of::<SomeI32>(),
align_of::<SomeI32>()); // 8 ⇒ 4
}
\end{minted}
\end{frame}
\section{Dialogue}
\begin{frame}[fragile]{Goal for today}
\begin{itemize}
\item Understanding how traits work
\item Understanding how generics work
\item Understanding a few type-system related properties/patterns
\item Understanding how rust models usecases covered by OOP, FP, concepts, contracts, interfaces, … $\Rightarrow$ discuss type systems
\end{itemize}
\end{frame}
% POSTPONED: pub?
% use {crate}::{package}::{trait}; ⇒ can implement it on their own. {trait} must be pub.
% public / private / protected?
% pub for individual struct members? Rust 1.41.0 release ⇒ https://github.com/rust-lang/rust/pull/66183/
\section{Dialogue: traits}
\begin{frame}[fragile]{struct}
\begin{minted}{rust}
struct Talk {
desc: String,
duration: u16,
}
\end{minted}
\end{frame}
\begin{frame}[fragile]{struct}
\begin{minted}{rust}
impl Talk {
fn new(text: &str) -> Talk {
Talk {
desc: text.to_string(),
duration: 45,
}
}
}
\end{minted}
A method \code{new} implemented over \code{struct} type \code{Talk}.
\end{frame}
\begin{frame}[fragile]{struct - \emph{not} like this!}
\begin{minted}{rust}
fn Talk::new() -> Talk {
Talk { desc: "foo", duration: 42 }
}
\end{minted}
\begin{minted}{text}
error: expected one of `(` or `<`, found `::`
\end{minted}
\begin{minted}{rust}
impl Talk {
fn new() -> Talk {
Talk { /*…*/ }
}
fn new() -> Talk {
Talk { /*…*/ }
}
}
\end{minted}
\begin{minted}{text}
error: duplicate definitions with name `new`
\end{minted}
\end{frame}
\begin{frame}[fragile]{traits}
\begin{minted}{rust}
trait Submission {
fn len(&self) -> u32;
fn summary(&self) -> String;
}
\end{minted}
\end{frame}
\begin{frame}[fragile]{traits cannot be instantiated}
\begin{minted}{rust}
fn main() {
let s: Submission;
}
\end{minted}
\begin{minted}[fontsize=\tiny]{text}
warning: trait objects without an explicit `dyn` are deprecated
--> src/main.rs:16:12
|
16 | let s: Submission;
| ^^^^^^^^^^ help: use `dyn`: `dyn Submission`
|
= note: `#[warn(bare_trait_objects)]` on by default
error[E0277]: the size for values of type `dyn Submission` cannot be known at compilation time
--> src/main.rs:16:9
|
16 | let s: Submission;
| ^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `dyn Submission`
= note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
= note: all local variables must have a statically known size
= help: unsized locals are gated as an unstable feature
\end{minted}
\end{frame}
\begin{frame}[fragile]{traits}
\begin{minted}{rust}
impl Submission for Talk {
fn len(&self) -> u32 {
self.duration as u32
}
fn summary(&self) -> String {
let dot = self.desc.find('.');
match dot {
Some(idx) => {
let mut s = String::new();
s.push_str(&self.desc[0..idx]);
s.push_str(" …");
s
},
None => self.desc.clone(),
} } }
\end{minted}
\end{frame}
\begin{frame}[fragile]{traits}
\begin{minted}{rust}
fn main() {
let t = Talk::new(concat!("Rust ",
"is a multi-paradigm system ",
"programming language focused ",
"on safety, especially safe ",
"concurrency. Rust is syntactically ",
"similar to C++, but is designed to ",
"provide better memory safety while ",
"maintaining high performance. In ",
"this talk I want to introduce ",
"listeners to the Rust programming ",
"language."));
println!("{}", t.summary());
}
\end{minted}
\end{frame}
\begin{frame}[fragile]{traits}
\begin{itemize}
\item If the first parameter of a method is \mintinline{rust}{&self} or \mintinline{rust}{&mut self}, an object is required.
\item \mintinline{rust}{t.summary()} is syntactic sugar for \mintinline{rust}{Talk::summary(t)}
\item Otherwise, we would call it a \emph{static} method in OOP.
\item \mintinline{rust}{trait} keyword to declare traits
\item \mintinline{rust}{impl <trait> for <struct>} for implementation
\item enums, structs, and unions can implement traits
\end{itemize}
\end{frame}
\begin{frame}[fragile]{traits coherence}
\begin{quote}
One restriction to note with trait implementations is that we can implement a trait on a type only if either the trait or the type is local to our crate.
This restriction is part of a property of programs called \emph{coherence}, and more specifically the \emph{orphan rule}, so named because the parent type is not present.
\end{quote}
Ensures that adding a dependency can't break your code.
\end{frame}
\begin{frame}[fragile]{traits coherence}
Can we implement trait \mintinline{rust}{fmt::Display} for our custom type? \textbf{Yes.} \\[15pt]
Can we implement our custom trait \mintinline{rust}{ToHTML} for type \mintinline{rust}{Vec<String>}? \textbf{Yes.} \\[15pt]
Can we implement trait \mintinline{rust}{fmt::Display} for type \mintinline{rust}{Vec<String>}? \textbf{No.}
\end{frame}
\begin{frame}[fragile]{traits coherence}
Rust release 1.41.0 (released 2020-01-30) includes \href{https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html}{RFC 2451}.
\enquote{Stabilize the \texttt{re\_rebalance\_coherence} feature} [\href{https://github.com/rust-lang/rust/pull/65879/}{PR~65879}]
\begin{quote}
For better or worse, we allow implementing foreign traits for foreign types. For example, \mintinline{rust}{impl From<Foo> for Vec<i32>} is something any crate can write, even though \mintinline{rust}{From} is a foreign trait, and \mintinline{rust}{Vec} is a foreign type. However, under the current coherence rules, we do not allow \mintinline{rust}{impl<T> From<Foo> for Vec<T>}.
\end{quote}
\end{frame}
\begin{frame}[fragile]{traits default behavior}
\begin{minted}{rust}
trait Submission {
fn len(&self) -> u32;
fn summary(&self) -> String;
fn mentions_rust(&self) -> bool {
true
}
}
\end{minted}
\mintinline{rust}{mentions_rust} provides a default implementation. Can be overidden by any implementation.
Adding one trait need not break backwards-compatibility ($\rightarrow$ extensibility).
It isn’t possible to call the default implementation from an overriding implementation of that same method.
\mintinline{rust}{Submission} cannot have any mutable fields like \mintinline{rust}{title: String}.
\end{frame}
\begin{frame}[fragile]{traits constants}
\begin{minted}{rust}
trait Submission {
const MAX_DURATION: u32 = 300;
fn len(&self) -> u32;
fn summary(&self) -> String;
fn mentions_rust(&self) -> bool {
true
}
}
\end{minted}
\end{frame}
\begin{frame}[fragile]{traits constants}
Example via stackoverflow: \href{https://stackoverflow.com/q/56718406}{Why does Rust assignment of const from trait to trait not work?}
\end{frame}
\begin{frame}[fragile]{traits constants}
\begin{minted}{rust}
trait A {
const X: i32 = 1;
}
struct S;
impl A for S {}
trait B {
const Y: i32 = A::X;
}
trait C {
const Y: i32 = S::X;
}
fn main() {
}
\end{minted}
\end{frame}
\begin{frame}[fragile]{traits constants}
\begin{itemize}
\item Does not compile.
\item In essence, any trait cannot depend on values of other traits.
\item Constants are constants. Not default values (for other types).
\end{itemize}
\end{frame}
\begin{frame}[fragile]{traits constants}
\begin{minted}[fontsize=\scriptsize]{rust}
trait A {
const X: i32 = 1;
}
struct S;
impl A for S {}
struct R;
impl A for R {
const X: i32 = 42;
}
fn main() {
println!("S: {}", S::X); // S: 1
println!("R: {}", R::X); // R: 42
// A::X alone is ambiguous
println!("S: {}", <S as A>::X); // S: 1
println!("R: {}", <R as A>::X); // R: 42
}
\end{minted}
\end{frame}
\begin{frame}[fragile]{traits constants}
\begin{minted}[fontsize=\scriptsize]{rust}
trait A {
fn get_x() -> i32 {
1
}
}
struct S;
impl A for S {}
struct R;
impl A for R {
fn get_x() -> i32 {
42
}
}
fn main() {
println!("S: {}", S::get_x()); // S: 1
println!("R: {}", R::get_x()); // R: 42
println!("S: {}", <S as A>::get_x()); // S: 1
println!("R: {}", <R as A>::get_x()); // R: 42
}
\end{minted}
\end{frame}
\begin{frame}[fragile]{traits default behavior}
\begin{minted}{rust}
fn submit_to_glt(sub: impl Submission) {
println!("Dear GLT-Team, we would like \
to submit the following talk: {}",
sub.summary());
}
\end{minted}
The parameter can be \emph{anything} satisfying the trait \emph{Submission}.
\end{frame}
\begin{frame}[fragile]{traits and trait bounds}
\begin{minted}{rust}
fn submit_to_glt<T: Submission>(sub: T) {
println!("Dear GLT-Team, we would like \
to submit the following talk: {}",
sub.summary());
}
\end{minted}
Another syntax.
This is called \emph{trait bound}.
\end{frame}
\begin{frame}[fragile]{traits and trait bound unions}
\begin{minted}{rust}
fn represent_submission
<T: Submission + Display>
(sub: T) {
// …
}
\end{minted}
The parameter must implement Submission \emph{and} Display.
\end{frame}
% TODO I never discussed whether/when “impl<T> Trait<T>” or “impl Trait<T>” is correct
\begin{frame}[fragile]{traits and trait bounds with where}
\begin{minted}{rust}
fn submit_to_glt<T>(sub: T)
where T: Submission {
println!("Dear GLT-Team, we would like \
to submit the following talk: {}",
sub.summary());
}
\end{minted}
More generic example:
\begin{minted}{rust}
impl <A, D> MyTrait<A, D> for YourType where
A: TraitB + TraitC,
D: TraitE + TraitF {}
\end{minted}
\end{frame}
\begin{frame}[fragile]{traits and trait bounds with bang}
\begin{minted}{rust}
impl <A, D> MyTrait<A, D> for YourType where
A: TraitB + TraitC,
D: !TraitE + TraitF {}
\end{minted}
This example does \emph{not} compile. \emph{Negative \texttt{!trait} bounds} were dropped (\href{https://github.com/rust-lang/rfcs/pull/586}{PR 586 \enquote{Negative bounds}}).
\end{frame}
\begin{frame}[fragile]{traits and ?Sized}
\begin{minted}{rust}
fn submit_to_glt<T: ?Sized>(sub: T) {
// …
}
\end{minted}
\href{https://github.com/rust-lang/rfcs/blob/master/text/0490-dst-syntax.md}{RFC 0490 DST syntax}. Only works for the \code{Sized} trait.
Generics must be sized per default (its size is known at compile-time).
But in some contexts it is allowed to be \enquote{maybe sized} (sized or unsized).
\end{frame}
\begin{frame}[fragile]{traits and trait bounds}
\begin{minted}{rust}
fn compare(sub1: impl Submission,
sub2: impl Submission) -> i8 {
if sub1.mentions_rust() &&
!sub2.mentions_rust() {
-1
} else if !sub1.mentions_rust() &&
sub2.mentions_rust() {
1
} else {
0
}
}
\end{minted}
\end{frame}
\begin{frame}[fragile]{traits and trait bounds}
\begin{minted}{rust}
fn compare<T: Submission>
(sub1: T, sub2: T) -> i8 {
if sub1.mentions_rust() &&
!sub2.mentions_rust() {
-1
} else if !sub1.mentions_rust() &&
sub2.mentions_rust() {
1
} else {
0
}
}
\end{minted}
\end{frame}
\begin{frame}[fragile]{traits and trait bounds}
\textbf{Question:} Are these trait bounds the same?
\pause
\begin{itemize}
\item No.
\item \mintinline{rust}{impl Submission} requires two implementations of \code{Submission}
\item \mintinline{rust}{<T: Submission>} requires two times the \emph{same} implementations of \code{Submission}
\end{itemize}
\end{frame}
\begin{frame}[fragile]{traits and trait bounds}
\begin{minted}{rust}
struct Talk {
desc: String,
duration: u16,
}
struct Workshop {
desc: String,
duration: u16,
}
impl Submission for Talk { /* … */ }
impl Submission for Workshop { /* … */ }
\end{minted}
\end{frame}
\begin{frame}[fragile]{traits and trait bounds}
\begin{minted}{rust}
compare(
Talk{
desc: String::from("This talk …"),
duration: 45
}, Workshop{
desc: String::from("In this workshop …"),
duration: 90
}
);
\end{minted}
\begin{minted}{text}
error[E0308]: mismatched types
[…]
expected struct `Talk`, found struct `Workshop`
\end{minted}
\end{frame}
\begin{frame}[fragile]{traits and trait bounds}
\begin{minted}{rust}
fn compare<T1: Submission, T2: Submission>
(sub1: T1, sub2: T2) -> i8 {
if sub1.mentions_rust() &&
!sub2.mentions_rust() {
-1
} else if !sub1.mentions_rust() &&
sub2.mentions_rust() {
1
} else {
0
}
}
\end{minted}
This covers the \code{(Talk, Workshop)} case, of course.
\end{frame}
\begin{frame}[fragile]{traits and trait bounds}
\begin{itemize}
\item A \emph{marker trait} is a trait requiring implementation of 0 methods. Used to \emph{mark} a property. See \href{https://doc.rust-lang.org/std/marker/trait.Send.html}{Send} and \href{https://doc.rust-lang.org/std/marker/trait.Sync.html}{Sync} traits.
\item We can also conditionally implement a trait for any type that implements another trait. Implementations of a trait on any type that satisfies the trait bounds are called \emph{blanket implementations} and are extensively used in the Rust standard library.
\item \emph{Auto traits} are \href{https://stackoverflow.com/a/49710956}{opt-in, built-in traits (OIBIT)} which are unstable and not covered here (\enquote{automatically implemented traits}). \enquote{Auto trait implementation} occur in the standard library.
\end{itemize}
\end{frame}
\begin{frame}[fragile]{standard library traits}
\begin{description}
\item[Iterator trait] discussed before.
\item[Add trait] implements operator overloading of the addition operator \mintinline{rust}{+}.
\item[Deref trait] is used for immutable dereferencing operations, like \mintinline{rust}{*val}. \mintinline{rust}{fn deref(&self) -> &Self::Target} is required.
\item[Drop trait] is used to run some code when a value goes out of scope. This is sometimes called a \emph{destructor}. \mintinline{rust}{fn drop(&mut self)} is required.
\end{description}
\end{frame}
\begin{frame}[fragile]{standard library traits}
\begin{description}
\item[Send trait] is a marker trait for types that can be transferred across thread boundaries.
\item[Sync trait] is a marker trait for types where it is safe to share references between threads.
\item[Display trait] format trait for an empty format; \mintinline{rust}{{}}.
\item[Debug trait] provides the output in a programmer-facing, debugging context; \mintinline{rust}{{:?}}.
\end{description}
Both require:
\begin{minted}{rust}
fmt(&self, f: &mut Formatter)
-> Result<(), Error>
\end{minted}
\end{frame}
% POSTPONED “use” trait and pub
% TODO sometimes it is necessary to “use” just the trait
% POSTPONED
% TODO associated type
% https://stackoverflow.com/a/54803174
% hetseq len.rs gives an example with colon(!) with "type Length: Num" inside its trait Length.
% Associated types can be defined (e.g. type Item;) inside a trait (e.g. std::iter::Iterator)
% indexing trait requires return type reference. But Rc is also a reference? One defined Output type.
% POSTPONED
% TODO trait objects as run time concept, type erasure
% rust supports static and dynamic dispatching.
% https://doc.rust-lang.org/1.30.0/book/first-edition/trait-objects.html
% https://doc.rust-lang.org/book/ch17-02-trait-objects.html
% `fn use(&Iterator)` illustrates dynamic dispatch with a vtable. Supports heterogeneity.
% `dyn/trait objects <https://doc.rust-lang.org/nightly/edition-guide/rust-2018/trait-system/more-container-types-support-trait-objects.html>`_
% `Rust notes: dynamic and global static objects <https://gist.github.com/DmitrySoshnikov/8439eac0a09d9fafe55a83c88d049117>`_
% POSTPONED
% TODO What is part of a trait signature w.r.t. to static & dynamic dispatch?
% POSTPONED
% TODO `What are Rust's exact auto-dereferencing rules? <https://stackoverflow.com/a/28552082>`_
\begin{frame}[fragile]{traits}
\textbf{Question:} Can we provide references to traits?
Not discussed today. Topic \emph{trait objects} and \emph{dynamic dispatch}.
% TODO Does it matter whether we are generic over T or &T?
% https://stackoverflow.com/questions/28005134/how-do-i-implement-the-add-trait-for-a-reference-to-a-struct
\end{frame}
\section{Dialogue: generics}
% POSTPONED
% `Learning Generics in Rust <https://tutorialedge.net/rust/learning-generics-in-rust/>`_
\begin{frame}[fragile]{type systems}
How can we maintain the DRY (Don't repeat yourself) principle in programming? \\[8pt]
Opinionated answer:
\begin{description}
\item[strongly typed language] Generics
\item[dynamically typed language] Duck typing
\end{description}
\end{frame}
\begin{frame}[fragile]{generics introduction}
\begin{minted}{rust}
use std::mem::{size_of,align_of};
fn main() {
println!("{} ⇒ {}", size_of::<i32>(),
align_of::<i32>()); // 4 ⇒ 4
println!("{} ⇒ {}", size_of::<u8>(),
align_of::<u8>()); // 1 ⇒ 1
println!("{} ⇒ {}", size_of::<*mut i32>(),
align_of::<*mut i32>()); // 8 ⇒ 8
println!("{} ⇒ {}", size_of::<usize>(),
align_of::<usize>()); // 8 ⇒ 8
println!("{} ⇒ {}", size_of::<char>(),
align_of::<char>()); // 4 ⇒ 4
}
\end{minted}
A more compact version would be nice.
\end{frame}
\begin{frame}[fragile]{generics introduction}
\begin{minted}{rust}
println!("{} ⇒ {}", size_of::<i32>(),
align_of::<i32>()); // 4 ⇒ 4
\end{minted}
\textbf{Goal:} make \mintinline{rust}{i32} parametrizable. This example does \emph{not} compile:
\begin{minted}{rust}
use std::mem::{size_of,align_of};
fn show(T) {
println!("{} ⇒ {}", size_of::<T>(),
align_of::<T>());
}
fn main() {
show::<i32>();
show::<u8>();
// …
}
\end{minted}
\end{frame}
\begin{frame}[fragile]{generics introduction}
\begin{minted}{rust}
use std::mem::{size_of,align_of};
fn show<T>() {
println!("{} ⇒ {}",
size_of::<T>(),
align_of::<T>());
}
fn main() {
show::<i32>(); // 4 ⇒ 4
show::<u8>(); // 1 ⇒ 1
// …
}
\end{minted}
This example compiles.
\end{frame}
\begin{frame}[fragile]{generics introduction}
{\Large We are generic over \emph{types}, not \emph{values}!} \\[5pt]
So we cannot define a vector with \texttt{N} elements, where the vector is generic over \texttt{N} (length is value, not type).
\end{frame}
\begin{frame}[fragile]{generics and monomorphization}
\begin{minted}{rust}
fn first<A, B>(tuple: (A, B)) -> A {
let (a, b) = tuple;
return a;
}
fn main() {
assert_eq!(1, first((1, 9)));
}
\end{minted}
\end{frame}
\begin{frame}[fragile]{generics and monomorphization}
How are generics implemented?
Generics are implemented using \emph{monomorphization}.
Monomorphization means specialized versions are generated for each type.
\begin{minted}{rust}
assert_eq!(1, first((1, 9)));
// version for integers is generated
assert_eq!('l', first(('l', 'p')));
// version for characters is generated
assert_eq!(3.14159, first((3.14159, 2.718281)));
// version for floats is generated
\end{minted}
Monomorphization is how C++ templates are implemented (unlike Java interfaces).
\end{frame}
\begin{frame}[fragile]{generics and monomorphization}
\begin{minted}{rust}
fn main() {
let mut i = (1, 9);
let mut c = ('l', 'p');
let mut f = (3.14159, 2.718281);
// avoids `first` to be inlined
i.1 += 99;
c.1 = 'r';
f.1 = 42.0;
assert_eq!(1, first(i));
assert_eq!('l', first(c));
assert_eq!(3.14159, first(f));
}
\end{minted}
\end{frame}
\begin{frame}[fragile]{generics and monomorphization}
\textbf{Advantage:} fast, specialized/optimized versions \\
\textbf{Disadvantage:} executable size increases \\[5pt]
Only the first \mintinline{rust}{first} call: 2,770,592 bytes \\
With two \mintinline{rust}{first} calls: 2,772,032 bytes \\
With three \mintinline{rust}{first} calls: 2,804,176 bytes \\[5pt]
Differences are +1440 and +32144 bytes. Cannot tell why it is a non-linear increase, but the point is that the executable size increases.
\end{frame}
% POSTPONED
% TODO monomorphisation and executable size
% `What is monomorphisation with context to C++? <https://stackoverflow.com/q/14189604>`_
% `fn use<T: Iterator>(t: T)` illustrates static dispatch (generic/parametric polymorphism). For each different choice of T, a custom compilation of use will be generated (enables optimization) (increases binary size) (like templates in C++).
% POSTPONED
% TODO generics
% unit structs: struct Nil; ⇒ instantiation always gives the same element? definition = instantiation? ⇒ Peano axioms
% `struct A;` versus `struct A {};`
% TODO generic arrays
% TODO dyn keyword ⇒ https://stackoverflow.com/a/50987296
\begin{comment}
% POSTPONED
struct Unit {}
trait Next {}
//impl Next for Unit {}
fn count(u: impl Next) -> u64 {
match u {
Next(v) => count(v) + 1,
Unit{} => 0,
}
}
fn main() {
let u = Unit {};
let t = Unit {};
println!("{:p}", &t);
println!("{:p}", &u);
println!("{}", count(Unit{}));
}
\end{comment}
% POSTPONED
% TODO there is no kind of dispatching, right? So no method name occurs twice and based on the traits, we dispatch
% `Wikipedia: Dependent type <https://en.wikipedia.org/wiki/Dependent_type>`_ not possible
% TODO which objects can be generic? functions? types?
% TODO newtype idiom
% https://doc.rust-lang.org/rust-by-example/generics/new_types.html
% `HackerNews: Phantom Types in Rust <https://news.ycombinator.com/item?id=6217314>`_ ⇒ `Phantom types in rust <https://bluishcoder.co.nz/2013/08/15/phantom_types_in_rust.html>`_
% https://doc.rust-lang.org/rust-by-example/generics/phantom.html
% Quiz: \item[Phantom types are] ~\uncover<8->{generic types that don't use all type parameters to allow distinct types with the same (effective) types}
% TODO typestate
% `The Typestate Pattern in Rust <http://cliffle.com/blog/rust-typestate/>`_
% `Typestate analysis <https://en.wikipedia.org/wiki/Typestate_analysis>`_
% `Typestate Is Dead, Long Live Typestate! <https://pcwalton.github.io/2012/12/26/typestate-is-dead.html>`_
% TODO find application in stdlib
\section{Dialogue: Algebraic data types}
\begin{frame}[fragile]{algebraic data types}
\begin{quote}
In computer programming, especially functional programming and type theory, an algebraic data type (ADT) is a kind of composite type, i.e., a type formed by combining other types. \\
---\href{https://en.wikipedia.org/wiki/Algebraic_data_type}{Wikipedia}
\end{quote}
\end{frame}
\begin{frame}[fragile]{algebraic data types}
\begin{minted}{rust}
use std::fmt;
enum List {
Nil,
Cons(Box<List>, u64),
}
\end{minted}
Algebraic? Sums and products. \code{List} is the sum of \code{Nil} and \code{Cons(\_)}. \code{Cons} is the product of \code{Box$<$List$>$} and \code{u64}.
Boxing? Avoids \mintinline{text}{recursive type `List` has infinite size}.
Article: \href{https://blog.softwaremill.com/algebraic-data-types-in-four-languages-858788043d4e}{Algebraic data types in four languages} (namely Haskell, Scala, rust, and TypeScript)
\end{frame}
\begin{frame}[fragile]{algebraic data types}
\begin{minted}{rust}
impl fmt::Display for List {
fn fmt(&self, f: &mut fmt::Formatter<'_>)
-> fmt::Result {
match self {
List::Cons(inner, item)
=> write!(f, "(cons {} {})", item, inner),
List::Nil
=> write!(f, "nil"),
}
}
}
\end{minted}
Recognize that \code{Cons} is addressed by \mintinline{rust}{List::Cons}.
\end{frame}
\begin{frame}[fragile]{algebraic data types}
\textbf{Call:}
\begin{minted}{rust}
fn main() {
println!("{}", List::Cons(Box::new(
List::Cons(Box::new(List::Nil), 1)), 2));
}
\end{minted}
\textbf{Output:}
\begin{minted}{text}
(cons 2 (cons 1 nil))
\end{minted}
\end{frame}
\begin{frame}[fragile]{algebraic data types}
\begin{minted}{rust}
use std::fmt;
enum Tree {
Node(Box<Tree>, Box<Tree>),
Leaf(u32),
Empty,
}
\end{minted}
\end{frame}
\begin{frame}[fragile]{algebraic data types}
\begin{minted}{rust}
impl fmt::Display for Tree {
fn fmt(&self, f: &mut fmt::Formatter<'_>)
-> fmt::Result {
match self {
Tree::Node(left, right)
=> write!(f, "({}, {})", left, right),
Tree::Leaf(item)
=> write!(f, "({})", item),
Tree::Empty
=> write!(f, "_"),
}
}
}
\end{minted}
\end{frame}