part 09: explain how Rust prevents iterator invalidation
[rust-101.git] / workspace / src / part05.rs
1 // Rust-101, Part 05: Clone
2 // ========================
3
4 // ## Big Numbers
5
6 pub struct BigInt {
7     pub data: Vec<u64>,
8 }
9
10 // Now that we fixed the data representation, we can start implementing methods on it.
11 impl BigInt {
12     pub fn new(x: u64) -> Self {
13         if x == 0 {
14             BigInt { data: vec![] }
15         } else {
16             unimplemented!()
17         }
18     }
19
20     pub fn test_invariant(&self) -> bool {
21         if self.data.len() == 0 {
22             true
23         } else {
24             unimplemented!()
25         }
26     }
27
28     // We can convert any vector of digits into a number, by removing trailing zeros. The `mut`
29     // declaration for `v` here is just like the one in `let mut ...`, it says that we will locally
30     // change the vector `v`.
31     // 
32     // **Exercise 05.1**: Implement this function.
33     // 
34     // *Hint*: You can use `pop()` to remove the last element of a vector.
35     pub fn from_vec(mut v: Vec<u64>) -> Self {
36         unimplemented!()
37     }
38 }
39
40 // ## Cloning
41 fn clone_demo() {
42     let v = vec![0,1 << 16];
43     let b1 = BigInt::from_vec((&v).clone());
44     let b2 = BigInt::from_vec(v);
45 }
46
47 impl Clone for BigInt {
48     fn clone(&self) -> Self {
49         unimplemented!()
50     }
51 }
52
53 // We can also make the type `SomethingOrNothing<T>` implement `Clone`. 
54 use part02::{SomethingOrNothing,Something,Nothing};
55 impl<T: Clone> Clone for SomethingOrNothing<T> {
56     fn clone(&self) -> Self {
57         unimplemented!()
58     }
59 }
60
61 // **Exercise 05.2**: Write some more functions on `BigInt`. What about a function that returns the number of
62 // digits? The number of non-zero digits? The smallest/largest digit?
63
64 // ## Mutation + aliasing considered harmful (part 2)
65 enum Variant {
66     Number(i32),
67     Text(String),
68 }
69 fn work_on_variant(mut var: Variant, text: String) {
70     let mut ptr: &mut i32;
71     match var {
72         Variant::Number(ref mut n) => ptr = n,
73         Variant::Text(_) => return,
74     }
75     /* var = Variant::Text(text); */                                /* BAD! */
76     *ptr = 1337;
77 }
78