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