forked from teivah/rust-cheatsheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
1920 lines (1586 loc) · 54.4 KB
/
main.rs
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
#![allow(unused)]
use std::cell::{Ref, RefCell, RefMut};
use std::cmp::Ordering;
use std::collections::HashMap;
use std::fmt::Formatter;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::ops::{Deref, DerefMut};
use std::rc::{Rc, Weak};
use std::sync::mpsc::channel;
use std::sync::{Arc, Mutex};
use std::{fmt, fs, io, thread};
mod utils;
fn main() {
cargo();
comment();
scalar_types();
variables();
const_static_variables();
heap_stack();
string();
tuples();
control_flow();
loops();
array();
vector();
functions();
structs();
enums();
closures();
hashmap();
traits();
generics();
pattern_matching();
destructure();
if_let();
formatted_print();
option();
let _ = result();
ownership();
copy();
borrowing();
dangling();
lifetimes();
panic();
iterator();
smart_pointers();
file();
sort();
// Concurrency
threads();
message_passing();
arc();
sync_send();
// Advanced features
unsafe_();
associated_types();
newtype();
alias();
never_type();
macros();
// Testing
testing();
}
fn cargo() {
/*
Cargo is Rust's build system and package manager
Useful commands:
- Build an app for testing:
$ cargo build
- Build an app for production (slowest to build but fastest at runtime because of optimizations)
$ cargo build --release
- Checks your code to make sure it compiles (doesn't produce an excutable):
$ cargo check
- Run an app:
$ cargo run
*/
}
/// A 3-slash comment is used to create an exportable documentation.
/// It supports **Markdown**.
/// It can be generated and visualized if the project is a library using `$ cargo doc --open`
fn comment() {
// Single line comment
/*
Multiline comment
*/
//! Adds documentation to the item that contains the comment instead of the item following the comment
//! In this case, the surrounding function: `comment`
}
fn scalar_types() {
/*
Rust scalar types:
- Signed integers: i8, i16, i32, i64, i128, and isize (pointer size, depends on the architecture)
- Unsigned integers: u8, u16, u32, u64, u128, and usize (pointer size, depends on the architecture)
- Floating points: f32, f64
- Character: char
- Boolean: bool
- The unit type () whose only possible value is an empty tuple ()
Note on variable names: to avoid compiler warnings with unused variables or functions, we can either:
- Name it _
- Or prefix it with _ (e.g., _length)
- Import #![allow(unused)] as done in this file
*/
// Type inference
let i = 1;
// The previous declaration is similar to this
let i: i32 = 1;
// We can set the type alongside with the value
let i = 1i8;
// bool
let b = false;
// char
let c = 'x';
}
fn variables() {
// Using let, a variable is immutable
let s = 1;
// The following line would trigger a compilation error
// s = 2;
// Using let mut, a variable is mutable
let mut s = 1;
// Now we can mutate m
s = 2;
// Shadowing: same name but different type
let shadowed = 1;
let shadowed = false;
// Conversion
let i: i64 = 1;
let j = i as i32;
// Variable names and functions are based on snake_case
let apple_price = 32;
}
fn const_static_variables() {
// Const (convention: SCREAMING_SNAKE_CASE; e.g., FOO_BAR_BAZ)
// Note that type inference doesn't work with constants
const FOO: f32 = 3.1;
// Or, we can create static variable
// The main difference between a constant and a static variable is that values in a static
// variable have a fixed address in memory
// Hence, accessing a static variable refers to the same date
// Whereas accessing a const duplicates the data whenever it's used
// Immutable static variable
static BAR: i32 = 3;
// Mutable static variable
static mut VAR: i32 = 3;
// A static variable can be mutable compared to a constant
// Yet, it requires to be done inside an unsafe block
unsafe {
VAR = 4;
}
}
fn heap_stack() {
/*
Stack: fixed size data (primitives or array of primitives)
Memory is recaptured after the variable goes out of scope
Default assignment is a copy
Heap: data with an unknown size at compile time or a size that might change
(vector, String, structs, etc.)
Memory is recaptured after the last owner goes out of scope
Default assignment is a transfer of ownership (see later)
The heap is slower than the stack for pushing and accessing data
*/
}
fn string() {
// String slice
// Immutable, allocated on the stack (if declared from a literal); otherwise, on the heap
let s: &str = "foo";
// Second type of string
// Mutable (it declared with mut), allocated on the heap
// A string is a wrapper over a Vec<u8>
// Note: The :: operator means that a function is associated to a type not to an instance (static in Java)
let mut s2: String = String::from("foo");
// Concatenation
// With String type
let mut s = String::from("abc");
s.push('d');
s.push_str("bar");
// With a string slice
let s1: &str = "foo";
let s2: &str = &[s1, "bar"].concat();
// Convert from and to string literal
let s1 = "abc";
let s2 = s1.to_string();
let s1 = s2.as_str();
// String slice is a reference to a subset of a string
// Range indices must occur at valid UTF-8 character boundaries
let s: String = String::from("foo");
let slice: &str = &s[1..2]; // o
let slice: &str = &s[..2]; // fo
let slice: &str = &s[1..]; // oo
let slice: &str = &s[..]; // foo
// If we create a string slice in the middle of a multibyte character, the program will panic
let s = String::from("д");
// let slice = &s[0..1];
// String format
let i = 1;
let s = format!["foo {}", i];
// String concatenation
let s1: String = String::from("foo");
let s2: String = String::from("bar");
let s: String = s1 + &s2;
// String slice concatenation
let s1: &str = "foo";
let s2: &str = "foo";
let s: String = s1.to_owned() + &s2.to_owned();
// The following operation is not possible
// A char can be encoded on multiple bytes
// Rust does not allow this as may access an invalid character on its own
// let c = s[0];
// Instead, we have to iterate to get each grapheme clusters (a letter)
for c in "foo".chars() {}
// Or we can slice the string to get particular bytes
let s: &str = &"foo"[..1];
// Note: the convention in the standard library is:
// * String: Owned variant
// * Str: Borrowed variant
// For example, the 0sString type is owned whereas 0sStr is borrowed
// String to int conversion
let s = "42";
let i: i32 = s.parse().unwrap();
}
fn tuples() {
// A tuple is a collection of values of different types
let t = (true, 1);
// Same as
let t: (bool, i32) = (true, 1);
// Assign elements from a tuple
let i: bool = t.0;
let j: i32 = t.1;
// Or with a single line
let (i, j) = t;
}
fn control_flow() {
// If/else
let i = 1;
if i < 2 {
// true
} else {
// false
}
// If/else assignment (similar to ternary operator)
let n: bool = if i == 5 { true } else { false };
}
fn loops() {
// For (included..excluded)
for i in 0..3 {}
// Reverse, end excluded
for i in (1..3).rev() {}
// Reverse, end included
for i in (1..=3).rev() {}
// While
// i has to be mutable
let mut i = 0;
while i <= 3 {
i += 1;
}
// Labelled while
let mut i = 0;
'while1: while i < 3 {
break 'while1;
}
// Loop without conditions
loop {
break;
}
// Loop assignement
let mut sum = 0;
let b: bool = loop {
sum += i;
i += 1;
if i == 3 {
break sum < 10; // Returns a boolean
}
};
// Enumerate
let v = vec![1, 2, 3];
for (index, value) in v.iter().enumerate() {
println!("index={}, value={}", index, value);
}
}
fn print_coordinates(&(x, y): &(i32, i32)) {
println!("x={}, y={}", x, y);
}
fn array() {
// Fixed size array of 5 i32 elements
let a = [1, 2, 3, 4, 5];
// Same as
let a: [i32; 5] = [1, 2, 3, 4, 5];
// Access element
let i = a[0];
// The following line does not compile as the array is not mutable
// a[1] = 10;
// In order to mutate it we have to declare it mutable
let mut a: [i32; 5] = [1, 2, 3, 4, 5];
a[1] = 10;
// Initializes the 5 elements to value 0
let a: [i32; 5] = [0; 5];
// Get array length: 5
let n = a.len();
// Create slice from array
// A slice is a pointer on an array (it is not resizable)
let p: &[i32] = &a;
// We cannot modify a slice regardless if the backed array is mutable or not
// s[1] = 6;
// Create slice from sub array (included/excluded)
let s = &a[1..3];
// Slice length is 2
let n = s.len();
// Array iteration
let a: [&str; 3] = ["foo", "bar", "baz"];
// Over each element index
for i in 0..a.len() {
let n = a[i];
}
// Or directly over each element
for element in a.iter() {
let n = element;
}
// Two-dimensional array initialization
let board = [[0u32; 4]; 4];
}
fn vector() {
// A vector is a variable length array
// It is backed by an array, with a length and capacity
// Initialization - 0 capacity
// The type has to be set: as we don't insert any values, Rust doesn't know what kind of
// elements we intend to store
let v: Vec<i32> = Vec::new();
// Initialization using a macro - 0 capacity
let v: Vec<i32> = vec![];
// Initialization with i32 values
let v = vec![1i32, 2, 3];
// Initialization with initial capacity and mutable
let mut v: Vec<i32> = Vec::with_capacity(10);
// Add element, added to index 0
v.push(10); // [10]
// Added to index 1
v.push(20); // [10, 20]
// Remove latest element
v.pop(); // [20]
// Get an element returns an option (see later)
let o: Option<&i32> = v.get(0);
// Accessing an index outside the vector will not panic, it returns a None (see later)
let o: Option<&i32> = v.get(100);
// We can also access an element directly using its index but in this case, accessing an index
// outside the vector will panic
// let o = v[100];
// Get vector length and capacity
let n = v.len();
let n = v.capacity();
// Iteration
let v = vec![1, 2, 3];
for i in v {
// We can access i
println!("i={}", i);
// But we can't modify the values of the vector
}
// We can't access v anymore as the iteration took the ownership of v (see ownership())
// println!("v={:?}", v);
// Note that the loop was the same as
// for i in v.iter() {}
// If we want to keep accessing v, we need an iteration reference (i is a &i32)
let v = vec![1, 2, 3];
for i in &v {}
println!("v={:?}", v);
// Mutable iteration (is is a &mut i32)
// Note that v has to be mutable
let mut v = vec![1, 2, 3];
for i in v.iter_mut() {
// Mutate the values of the vector
*i = *i * 2;
}
println!("v={:?}", v);
// Copy a vector
let v = vec![1i32, 2, 3].to_vec();
let mut v = vec![1, 2, 3];
let first = &v[0];
v.push(4);
// The following line doesn't compile
// Indeed, when we push an element, the vector might require allocating new memory and copying
// the old elements to the new space. In that case, the reference to the first element would
// be pointing to deallocated memory.
// println!("{}", first);
}
fn functions() {
// Function call
let n = increment(1);
// Higher order function
let f = increment;
// Same as
let f: fn(i32) -> i32 = increment;
let n = f(1);
// Partially applied function
let partially_applied_functions = |x| multiply(3, x);
let f = partially_applied_functions(6);
}
// A simple function example
fn increment(a: i32) -> i32 {
// The latest expression is the value returned
a + 1
// Equivalent to
// return a + 1;
/*
Omitting return works only if the expression is the latest statement.
For example, the following doesn't compile:
fn calculate_price_of_apples(apples: i32) -> i32 {
if apples > MAX {
apples
}
apples * 2
}
Indeed, the `apples` statement isn't the last one of the function.
Yet, the following code compiles:
fn calculate_price_of_apples(apples: i32) -> i32 {
if apples > MAX {
apples
} else {
apples * 2
}
}
*/
}
// Another simple function example
fn multiply(a: i32, b: i32) -> i32 {
a * b
}
fn structs() {
// 3 types of structs: structs (C-like), tuple structs and unit structs
// A structure is immutable by default
/* Structs (C-like) */
// We need to assign a value for each member of the structure otherwise it won't compile
let person = CLikePerson {
name: "foo".to_string(),
age: 18,
};
// Access
let s = person.name;
let s = person.age;
// Copy elements
let s = CLikePerson {
name: "bar".to_string(),
..person // Copy the rest of the elements, does not compile without it
};
// If we hold variables whose name are the same than the fields, we can pass them directly
let name = String::from("foo");
let age = 1;
let p = CLikePerson { name, age };
let person = CLikePerson {
name: "foo".to_string(),
age: 18,
};
// Note: Using the :? specifier inside the brackets tells println! to use the Debug output format
// It's possible because the struct has the #[derive(Debug)] annotation
println!("{:?}", person);
// The :#? specifier prints each field in a new line
println!("{:#?}", person);
// There are three types of methods
// 1. Calling using a &self
// The method doesn't take ownership and can't mutate the structure
person.method1();
// 2. Passing a &mut self allowing the structure to be mutated within the method
let mut mutable_person = CLikePerson {
name: String::from("foo"),
age: 18,
};
mutable_person.method2();
// 3. Transferring the ownership of the structure (see ownership())
person.method3();
/* Tuple structs */
let tuple_person = TuplePerson(String::from("foo"), 20);
// Accessing elements
let n = tuple_person.0;
/* Unit-like structs */
// A simple structure without members
// Useful in situation where we have to implement a trait on some type
// But we don't have any data that we want to store in the type itself
let n = UnitStruct;
}
// C-like structure
// The naming convention for each structure type is pascal case
#[derive(Debug)]
struct CLikePerson {
name: String,
age: u32,
}
impl CLikePerson {
fn method1(&self) {
// The structure cannot be mutated so the following line will not compile
// self.age = 20;
}
fn method2(&mut self) {
// This time, the structure can be mutated
self.age = 20;
}
fn method3(self) {}
// An impl block can also contain functions called associated functions
// Use cases: constructors or functions used only by methods of CLikePerson
fn factory(name: String, age: u32) -> CLikePerson {
CLikePerson { name, age }
}
}
// Note that it's allowed to have multiple impl blocks for the same struct
impl CLikePerson {}
// Tuple structure
struct TuplePerson(String, u32);
// Unit structure
struct UnitStruct;
fn enums() {
// Simple enum (based on units)
let e = Enum::Foo;
let e = Enum::Bar;
// Enum with variants
let e = EnumWithVariants::Foo { id: 1, age: 1 };
let e = EnumWithVariants::Bar(String::from("foo"));
let e = EnumWithVariants::Baz;
}
enum Enum {
Foo,
Bar,
}
enum EnumWithVariants {
Foo { id: i32, age: i32 }, // Struct variant
Bar(String), // Tuple variant
Baz, // Unit
}
fn closures() {
// Three types of closure
// FnOnce: consume the variables it captures (all closures implement FnOnce as they can all be called at least once)
// FnMut: mutable borrow (if closure don't move the captured variables)
// Fn: immutable borrow
// Closure example
let x = 1;
let c = |y: i32| -> i32 { x + y };
println!("closure result: {}", c(2));
// We're not obliged to annotate the type of the parameters or the return value like fn functions do
let x = 5;
let mut y;
let c = |v| v + 1;
y = c(x);
// To force a closure to take ownership of the values we can use move keyword
let c = move |x: Point| -> Point { x };
// Direct closure call
let c: i32 = { 1 + 2 };
// A struct can hold a function
let s = StructWithFunction { f: |x| x + 1 };
let n = (s.f)(1);
// In case of a closure (variable v is moved), the struct has to use generics
let v = 1;
let s = StructWithClosure { f: |x| x + v };
let n = (s.f)(1);
// A function can also accept a closure
function_accepting_closure(1, 2, |a, b| a + b);
// We could have also passed a function like so
function_accepting_closure(1, 2, add);
// A function retuning a fn type can't return a closure directly
}
struct StructWithFunction {
f: fn(i32) -> i32,
}
struct StructWithClosure<T>
where
T: Fn(u32) -> u32,
{
f: T,
}
fn function_accepting_closure(a: i32, b: i32, f: fn(i32, i32) -> i32) -> i32 {
return f(a, b);
}
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn hashmap() {
// Hashmap creation
let m: HashMap<String, i32> = HashMap::new();
// With initial capacity
let mut map: HashMap<String, i32> = HashMap::with_capacity(32);
// Note: a map stores its data on the heap
// Insert elements
let s = String::from("one");
let i = 1;
map.insert(s, i);
// If a type implements the Copy trait (e.g. i32), the values are copied into the hash map
// Hence it is valid to reuse i
let n = i;
// Otherwise, the values are moved
// Hence, as it is invalid to reuse s, the following line wille not compile
// let s2 = s;
// Insert if the key does not already exist
let v: &mut i32 = map.entry(String::from("two")).or_insert(2);
// We can also mutate the entry value directly
*v = 20;
// Iteration
// key is an &String whereas value is an &i32
for (key, value) in &map {}
// Using an iter
map.iter()
.for_each(|(key, value)| println!("{}{}", key, value));
// Create a hashmap from two vectors
let v1 = vec![
String::from("one"),
String::from("two"),
String::from("three"),
];
let v2 = vec![1, 2, 3];
// The <_, _> notation is needed as it's possible to collect into many different data structures
// So Rust doesn't know which one we want unless it's specified
let m: HashMap<_, _> = v1.iter().zip(v2.iter()).collect();
}
fn traits() {
// An impl is used to define method for structs and enums
let p = Point { x: 1, y: 1 }.foo(Point { x: 2, y: 2 });
// An associated (static) function call
let point = Point::new(1, 1);
// A trait can be seen as a contract, it's similar to interfaces in other
// languages, with some differences
// A trait can be a parameter
function_accepting_trait(Point::new(1, 1));
// A syntax variant called *trait bound* syntax
// The previous variant is a syntax sugar
function_accepting_trait_variant(Point::new(1, 1));
// The trait bound syntax is useful for specific use cases. For example, if we want to
// enforce two parameters to have the same type.
function_accepting_two_parameters_of_the_same_type(Point::new(1, 1), Point::new(1, 1));
// A function can also return a trait
let t = function_returning_trait();
// Note: it's only possible if the function returns a single type
// For example, if `function_returning_trait` was returning two possible types implementing
// `Trait`, the function wouldn't compile
// Point also implements the generic trait TraitWithGenerics
let p = Point::convert_to_tuple(Point { x: 1, y: 1 });
// Inheritance example
// Ferrari implementing the Vehicle and Car traits
let f = Ferrari {
id: String::from("001"),
color: String::from("red"),
};
// Note: one restriction with trait implementation is that we can implement a trait on a type
// only if:
// * Either the trait is local to our crate
// * Or if the type is local to our crate
// We can't implement external traits on external types
// Method calls on trait objects (dyn Trait) works only with traits which are object safe
// A trait is object safe if all the methods defined in the traits have the following properties:
// * The return type isn't Self
// * There are no generic type parameters
}
struct Point {
x: i32,
y: i32,
}
// A collection of methods on Point structure
impl Point {
fn foo(self, point: Point) -> Point {
Point {
x: self.x + point.x,
y: self.y + point.y,
}
}
// Associated function (static)
// It does not take a self argument
fn new(a: i32, b: i32) -> Self {
Point { x: a, y: b }
}
}
fn function_accepting_trait(a: impl Trait) {
a.default_method();
}
fn function_accepting_trait_variant<T: Trait>(a: T) {
a.default_method();
}
fn function_accepting_two_parameters_of_the_same_type<T: Trait>(a: T, b: T) {
a.default_method();
b.default_method();
}
fn function_returning_trait() -> impl Trait {
Point { x: 1, y: 1 }
}
// Trait example
trait Trait {
fn add(&self, p2: Point) -> Point;
// An interface can also have default methods
fn default_method(&self) {
println!("default method");
}
}
// The implementation of the trait has to be done explicitely
impl Trait for Point {
fn add(&self, point: Point) -> Point {
Point {
x: self.x + point.x,
y: self.y + point.y,
}
}
}
// Trait with generics
trait TraitWithGenerics<T> {
fn convert_to_tuple(t: T) -> (i32, i32);
}
impl TraitWithGenerics<Point> for Point {
fn convert_to_tuple(point: Point) -> (i32, i32) {
(point.x, point.y)
}
}
trait Vehicle {
fn id(self) -> String;
}
// Car inherits from vehicle
trait Car: Vehicle {
fn color(self) -> String;
}
struct Ferrari {
id: String,
color: String,
}
// CarImpl has to implement both traits: Vehicle and Car
// Vehicle implementation
impl Vehicle for Ferrari {
fn id(self) -> String {
self.id
}
}
// Car implementation
impl Car for Ferrari {
fn color(self) -> String {
self.color
}
}
fn generics() {
// Generics in Rust do not have any performance impact
// Rust accomplishes this using monomorphization
// It is the process of turning generic code into specific code at compile time
// Generic function call
// The function accepts only structures implementing Trait
let p = generic_function(Point { x: 1, y: 1 }, Point { x: 1, y: 1 });
// This is different that the following function that accepts Trait implementation
let p = function_accepting_implementation(Point { x: 1, y: 1 }, Point { x: 1, y: 1 });
// In the first example, we have to passe the same structure type
// In the second example, we can pass two different structure types as long as they both implement Trait
// A function can also specify multiple traits
specifying_multiple_trait(utils::Struct {}, utils::Struct {});
// An alternative syntax
specifying_multiple_trait_alternative_syntax(utils::Struct {}, utils::Struct {});
// Instantiate a generic structure
let s = GenericStruct { x: 1, y: 2 };
println!("{} {}", s.x, s.y);
// A generic implementation
let p = s.generic_function();
// A specific implementation for GenericStruct<i32> only
let i = s.specific_function();
let s = GenericStruct { x: "a", y: "b" };
// Doesn't compile
// s.specific_function();
// Instantiate a generic enum
let p = GenericEnum::<i32, String>::Foo(1);
let p = GenericEnum::<i32, String>::Bar("foo".to_string());
}
fn generic_function<T: Trait>(x: T, _: T) -> T {
x
}
fn function_accepting_implementation(x: impl Trait, _: impl Trait) -> impl Trait {
x
}
fn specifying_multiple_trait<T: utils::Trait1 + utils::Trait2>(x: T, _: T) -> T {
x
}
fn specifying_multiple_trait_alternative_syntax<T>(x: T, _: T) -> T
where
T: utils::Trait1 + utils::Trait2,
{
x
}
struct GenericStruct<T> {
x: T,
y: T,
}
impl<T> GenericStruct<T> {
fn generic_function(&self) -> &T {
&self.x
}
}
impl GenericStruct<i32> {
fn specific_function(&self) -> i32 {
self.x + self.y
}
}
enum GenericEnum<T, E> {
Foo(T),
Bar(E),
}
fn pattern_matching() {
// Pattern matching on an integer
let i = 1;
// The match has to cover all the cases
// The following example does not compile if we omit the last case
let n = match i {
0 => "zero",
1 => "one",
_ => "other", // Other cases
};
// If we want to do nothing
let n = match i {
0 => println!("zero"),
_ => (), // () is the unit value, so nothing will happen in this case
};
// Comparing integers
// It uses std::cmp::Ordering
let i = 1;
let j = 2;
let n = match i.cmp(&j) {
Ordering::Less => "less",
Ordering::Greater => "greater",
Ordering::Equal => "equals",
};
// Matching multiple options
let level = 22;
let n = match level {
1 | 2 => "beginner",
_ => "other",
};
// Matching an interval
let level = 22;
let n = match level {
1..=5 => "beginner",
6..=10 => "intermediate",
11..=20 => "expert",
_ => "other",
};
let c = 'x';
match c {
'a'..='j' => (),
'k'..='z' => (),
_ => (),
}