part07.rs lines shortened
[rust-101.git] / src / part07.rs
1 // Rust-101, Part 07: Operator Overloading, Tests, Formatting
2 // ==========================================================
3
4 pub use part05::BigInt;
5
6 // With our new knowledge of lifetimes, we are now able to write down the desired type of `min`:
7 //@ We want the function to take two references *with the same lifetime*, and then
8 //@ return a reference with that lifetime. If the two input lifetimes would be different, we
9 //@ would not know which lifetime to use for the result.
10 pub trait Minimum {
11     fn min<'a>(&'a self, other: &'a Self) -> &'a Self;
12 }
13
14 //@ Now we can implement a generic function `vec_min` that works on above trait.
15 //@ The code is pretty much straight-forward, and Rust checks that all the
16 //@ lifetimes actually work out. Observe that we don't have to make any copies!
17 pub fn vec_min<T: Minimum>(v: &Vec<T>) -> Option<&T> {
18     let mut min: Option<&T> = None;
19     for e in v {
20         min = Some(match min {
21             None => e,
22             Some(n) => n.min(e)
23         });
24     }
25     min
26 }
27 //@ Notice that the return type `Option<&T>` is technically (leaving the borrowing story aside) a
28 //@ pointer to a `T`, that could optionally be invalid. In other words, it's just like a pointer in
29 //@ C(++) or Java that can be `NULL`! However, thanks to `Option` being an `enum`, we cannot forget
30 //@ to check the pointer for validity, avoiding the safety issues of C(++). <br/>
31 //@ Also, if you are worried about wasting space, notice that Rust knows that `&T` can never be
32 //@ `NULL`, and hence optimizes `Option<&T>` to be no larger than `&T`. The `None` case is
33 //@ represented as `NULL`. This is another great example of a zero-cost abstraction: `Option<&T>`
34 //@ is exactly like a pointer in C(++), if you look at what happens during execution - but it's
35 //@ much safer to use.
36
37 // **Exercise 07.1**: For our `vec_min` to be usable with `BigInt`, you will have to provide an
38 // **implementation of `Minimum`. You should be able to pretty much copy the code you wrote for
39 // **exercise 06.1. You should *not* make any copies of `BigInt`!
40 impl Minimum for BigInt {
41     fn min<'a>(&'a self, other: &'a Self) -> &'a Self {
42         unimplemented!()
43     }
44 }
45
46 // ## Operator Overloading
47
48 //@ How can we know that our `min` function actually does what we want it to do? One possibility
49 //@ here is to do *testing*. Rust comes with nice built-in support for both unit tests and
50 //@ integration tests. However, before we go there, we need to have a way of checking whether the
51 //@ results of function calls are correct. In other words, we need to define how to test equality
52 //@ of `BigInt`. Being able to test equality is a property of a type, that - you guessed it - Rust
53 //@ expresses as a trait: `PartialEq`.
54
55 //@ Doing this for `BigInt` is fairly easy, thanks to our requirement that there be no trailing
56 //@ zeros. We simply re-use the equality test on vectors, which compares all the elements
57 //@ individually.
58 //@ The `inline` attribute tells Rust that we will typically want this function to be inlined.
59 impl PartialEq for BigInt {
60     #[inline]
61     fn eq(&self, other: &BigInt) -> bool {
62         debug_assert!(self.test_invariant() && other.test_invariant());
63         self.data == other.data                                     /*@*/
64     }
65 }
66
67 //@ Since implementing `PartialEq` is a fairly mechanical business, you can let Rust automate this
68 //@ by adding the attribute `derive(PartialEq)` to the type definition. In case you wonder about
69 //@ the "partial", I suggest you check out the documentation of
70 //@ [`PartialEq`](https://doc.rust-lang.org/std/cmp/trait.PartialEq.html) and
71 //@ [`Eq`](https://doc.rust-lang.org/std/cmp/trait.Eq.html). `Eq` can be automatically derived as
72 //@ well.
73
74 // Now we can compare `BigInt`s. Rust treats `PartialEq` special in that it is wired to the operator
75 // `==`:
76
77 //@ That operator can now be used on our numbers! Speaking in C++ terms, we just overloaded the
78 //@ `==` operator for `BigInt`. Rust does not have function overloading (i.e., it will not dispatch
79 //@ to different functions depending on the type of the argument). Instead, one typically finds (or
80 //@ defines) a trait that catches the core characteristic common to all the overloads, and writes a
81 //@ single function that's generic in the trait. For example, instead of overloading a function for
82 //@ all the ways a string can be represented, one writes a generic functions over
83 //@ [ToString](https://doc.rust-lang.org/std/string/trait.ToString.html).
84 //@ Usually, there is a trait like this that fits the purpose - and if there is, this has the great
85 //@ advantage that any type *you* write, that can convert to a string, just has to implement
86 //@ that trait to be immediately usable with all the functions out there that generalize over
87 //@ `ToString`.
88 //@ Compare that to C++ or Java, where the only chance to add a new overloading variant is to
89 //@ edit the class of the receiver.
90 //@ 
91 //@ Why can we also use `!=`, even though we just overloaded `==`? The answer lies in what's called
92 //@ a *default implementation*. If you check out the documentation of `PartialEq` I linked above,
93 //@ you will see that the trait actually provides two methods: `eq` to test equality, and `ne` to
94 //@ test inequality. As you may have guessed, `!=` is wired to `ne`. The trait *definition* also
95 //@ provides a default implementation of `ne` to be the negation of `eq`. Hence you can just
96 //@ provide `eq`, and `!=` will work fine. Or, if you have a more efficient way of deciding
97 //@ inequality, you can provide `ne` for your type yourself.
98 fn compare_big_ints() {
99     let b1 = BigInt::new(13);
100     let b2 = BigInt::new(37);
101     println!("b1 == b1: {} ; b1 == b2: {}; b1 != b2: {}", b1 == b1, b1 == b2, b1 != b2);
102 }
103
104 // ## Testing
105 // With our equality test written, we are now ready to write our first testcase.
106 //@ It doesn't get much simpler: You just write a function (with no arguments or return value),
107 //@ and give it the `test` attribute. `assert!` is like `debug_assert!`, but does not get compiled
108 //@ away in a release build.
109 #[test]
110 fn test_min() {
111     let b1 = BigInt::new(1);
112     let b2 = BigInt::new(42);
113     let b3 = BigInt::from_vec(vec![0, 1]);
114
115     assert!(*b1.min(&b2) == b1);                                    /*@*/
116     assert!(*b3.min(&b2) == b2);                                    /*@*/
117 }
118 // Now run `cargo test` to execute the test. If you implemented `min` correctly, it should all work!
119
120 // ## Formatting
121 //@ There is also a macro `assert_eq!` that's specialized to test for equality, and that prints the
122 //@ two values (left and right) if they differ. To be able to do that, the macro needs to know how
123 //@ to format the value for printing. This means that we - guess what? - have to implement an
124 //@ appropriate trait. Rust knows about two ways of formatting a value: `Display` is for pretty-
125 //@ printing something in a way that users can understand, while `Debug` is meant to show the
126 //@ internal state of data and targeted at the programmer. The latter is what we want for
127 //@ `assert_eq!`, so let's get started.
128
129 // All formating is handled by [`std::fmt`](https://doc.rust-lang.org/std/fmt/index.html). I won't
130 // explain all the details, and refer you to the documentation instead.
131 use std::fmt;
132
133 //@ In the case of `BigInt`, we'd like to just output our internal `data` array, so we
134 //@ simply call the formating function of `Vec<u64>`.
135 impl fmt::Debug for BigInt {
136     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
137         self.data.fmt(f)
138     }
139 }
140 //@ `Debug` implementations can be automatically generated using the `derive(Debug)` attribute.
141
142 // Now we are ready to use `assert_eq!` to test `vec_min`.
143 /*#[test]*/
144 fn test_vec_min() {
145     let b1 = BigInt::new(1);
146     let b2 = BigInt::new(42);
147     let b3 = BigInt::from_vec(vec![0, 1]);
148
149     let v1 = vec![b2.clone(), b1.clone(), b3.clone()];
150     let v2 = vec![b2.clone(), b3.clone()];
151     assert_eq!(vec_min(&v1), Some(&b1));                            /*@*/
152     assert_eq!(vec_min(&v2), Some(&b2));                            /*@*/
153 }
154
155 // **Exercise 07.1**: Add some more testcases. In particular, make sure you test the behavior of
156 // `vec_min` on an empty vector. Also add tests for `BigInt::from_vec` (in particular, removing
157 // trailing zeros). Finally, break one of your functions in a subtle way and watch the test fail.
158 // 
159
160 // **Exercise 07.2**: Go back to your good ol' `SomethingOrNothing`, and implement `Display` for it.
161 // (This will, of course, need a `Display` bound on `T`.) Then you should be able to use them with
162 // `println!` just like you do with numbers, and get rid of the inherent functions to print
163 // `SomethingOrNothing<i32>` and `SomethingOrNothing<f32>`.
164
165 //@ [index](main.html) | [previous](part06.html) | [raw source](workspace/src/part07.rs) |
166 //@ [next](part08.html)