add all the parts in workspace's main.rs
[rust-101.git] / workspace / src / part06.rs
1 // Rust-101, Part 06: Copy, Lifetimes
2 // ==================================
3
4 // We continue to work on our `BigInt`, so we start by importing what we already established.
5 use part05::BigInt;
6
7 // With `BigInt` being about numbers, we should be able to write a version of `vec_min`
8 // that computes the minimum of a list of `BigInt`. First, we have to write `min` for `BigInt`.
9 impl BigInt {
10     fn min_try1(self, other: Self) -> Self {
11         debug_assert!(self.test_invariant() && other.test_invariant());
12         // Now our assumption of having no trailing zeros comes in handy:
13         // If the lengths of the two numbers differ, we already know which is larger.
14         if self.data.len() < other.data.len() {
15             self
16         } else if self.data.len() > other.data.len() {
17             other
18         } else {
19             // **Exercise 06.1**: Fill in this code.
20             unimplemented!()
21         }
22     }
23 }
24
25 // Now we can write `vec_min`.
26 fn vec_min(v: &Vec<BigInt>) -> Option<BigInt> {
27     let mut min: Option<BigInt> = None;
28     for e in v {
29         unimplemented!()
30     }
31     min
32 }
33
34 // ## `Copy` types
35
36 use part02::{SomethingOrNothing,Something,Nothing};
37 impl<T: Copy> Copy for SomethingOrNothing<T> {}
38
39
40 // ## Lifetimes
41
42 fn head<T>(v: &Vec<T>) -> Option<&T> {
43     if v.len() > 0 {
44         unimplemented!()
45     } else {
46         None
47     }
48 }
49 // Technically, we are returning a pointer to the first element. But doesn't that mean that callers have to be
50 // careful? Imagine `head` would be a C++ function, and we would write the following code.
51 /*
52   int foo(std::vector<int> v) {
53     int *first = head(v);
54     v.push_back(42);
55     return *first;
56   }
57 */
58 fn rust_foo(mut v: Vec<i32>) -> i32 {
59     let first: Option<&i32> = head(&v);
60     /* v.push(42); */
61     *first.unwrap()
62 }
63
64