Java actually doesn't do pointer checks all the time
[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
7 // of `min`: We want the function to take two borrows *of the same lifetime*, and then
8 // return a borrow of 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.
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 represented
33 // as `NULL`. This is another great example of a zero-cost abstraction: `Option<&T>` is exactly like
34 // a pointer in C(++), if you look at what happens during execution - but it's much safer to use.
35
36 // For our `vec_min` to be usable with `BigInt`, we need to provide an implementation of
37 // `Minimum`. You should be able to pretty much copy the code you wrote for exercise 06.1.
38 impl Minimum for BigInt {
39     fn min<'a>(&'a self, other: &'a Self) -> &'a Self {
40         unimplemented!()
41     }
42 }
43
44 // ## Operator Overloading
45 // How can we know that our `min` function actually does what we want it to do? One possibility
46 // here is to do *testing*. Rust comes with nice build-in support for both unit tests and integration
47 // tests. However, before we go there, we need to have a way of checking whether the results of function calls are
48 // correct. In other words, we need to define how to test equality of `BigInt`. Being able to
49 // test equality is a property of a type, that - you guessed it - Rust expresses as a trait: `PartialEq`.
50
51 // Doing this for `BigInt` is fairly easy, thanks to our requirement that there be no trailing zeros.
52 // The `inline` attribute tells Rust that we will typically want this function to be inlined.
53 impl PartialEq for BigInt {
54     #[inline]
55     fn eq(&self, other: &BigInt) -> bool {
56         debug_assert!(self.test_invariant() && other.test_invariant());
57         self.data == other.data
58     }
59 }
60 // Since implementing `PartialEq` is a fairly mechanical business, you can let Rust automate this
61 // by adding the attribute `derive(PartialEq)` to the type definition. In case you wonder about
62 // the "partial", I suggest you check out the documentation of [`PartialEq`](http://doc.rust-lang.org/std/cmp/trait.PartialEq.html)
63 // and [`Eq`](http://doc.rust-lang.org/std/cmp/trait.Eq.html). `Eq` can be automatically derived as well.
64
65 // Now we can compare `BigInt`s using `==`! Speaking in C++ terms, we just overloaded the `==` operator
66 // for `BigInt`. Rust does not have function overloading (i.e., it will not dispatch to different
67 // functions depending on the type of the argument). Instead, one typically finds (or defines) a
68 // trait that catches the core characteristic common to all the overloads, and writes a single
69 // function that's generic in the trait. For example, instead of overloading a function for all
70 // the ways a string can be represented, one writes a generic functions over [ToString](http://doc.rust-lang.org/std/string/trait.ToString.html).
71 // Usually, there is a trait like this that fits the purpose - and if there is, this has the great
72 // advantage that any type *you* write, that can convert to a string, just has to implement
73 // that trait to be immediately usable with all the functions out there that generalize over `ToString`.
74 // Compare that to C++ or Java, where the only chance to add a new overloading variant is to
75 // edit the class of the receiver.
76 fn compare_big_ints() {
77     let b1 = BigInt::new(13);
78     let b2 = BigInt::new(37);
79     println!("b1 == b1: {} ; b1 == b2: {}; b1 != b2: {}", b1 == b1, b1 == b2, b1 != b2);
80 }
81
82 // ## Testing
83 // With our equality test written, we are now ready to write our first testcase. It doesn't get much
84 // simpler: You just write a function (with no arguments or return value), and give it the `test` attribute.
85 // `assert!` is like `debug_assert!`, but does not get compiled away in a release build.
86 #[test]
87 fn test_min() {
88     let b1 = BigInt::new(1);
89     let b2 = BigInt::new(42);
90     let b3 = BigInt::from_vec(vec![0, 1]);
91
92     assert!(*b1.min(&b2) == b1);
93     assert!(*b3.min(&b2) == b2);
94 }
95 // Now run `cargo test` to execute the test. If you implemented `min` correctly, it should all work!
96
97 // ## Formatting
98 // There is also a macro `assert_eq!` that's specialized to test for equality, and that prints the two
99 // values (left and right) if they differ. To be able to do that, the macro needs to know how to format
100 // the value for printing. This means that we - guess what? - have to implement an appropriate trait.
101 // Rust knows about two ways of formatting a value: `Display` is for pretty-printing something in a way
102 // that users can understand, while `Debug` is meant to show the internal state of data and targeted at
103 // the programmer. The latter is what we want for `assert_eq!`, so let's get started.
104
105 // All formating is handled by [`std::fmt`](http://doc.rust-lang.org/std/fmt/index.html). I won't explain
106 // all the details, and refer you to the documentation instead.
107 use std::fmt;
108
109 // In the case of `BigInt`, we'd like to just output our internal `data` array, so we
110 // simply call the formating function of `Vec<u64>`.
111 impl fmt::Debug for BigInt {
112     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
113         self.data.fmt(f)
114     }
115 }
116 // `Debug` implementations can be automatically generated using the `derive(Debug)` attribute.
117
118 // Now we are ready to use `assert_eq!` to test `vec_min`.
119 #[test]
120 fn test_vec_min() {
121     let b1 = BigInt::new(1);
122     let b2 = BigInt::new(42);
123     let b3 = BigInt::from_vec(vec![0, 1]);
124
125     let v1 = vec![b2.clone(), b1.clone(), b3.clone()];
126     let v2 = vec![b2.clone(), b3.clone()];
127     assert_eq!(vec_min(&v1), Some(&b1));
128     assert_eq!(vec_min(&v2), Some(&b2));
129 }
130
131 // **Exercise 07.1**: Add some more testcases. In particular, make sure you test the behavior of
132 // `vec_min` on an empty vector. Also add tests for `BigInt::from_vec` (in particular, removing
133 // trailing zeros). Finally, break one of your functions in a subtle way and watch the test fail.
134 // 
135 // **Exercise 07.2**: Go back to your good ol' `SomethingOrNothing`, and implement `Display` for it. (This will,
136 // of course, need a `Display` bound on `T`.) Then you should be able to use them with `println!` just like you do with numbers.
137
138 // [index](main.html) | [previous](part06.html) | [next](main.html)