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