1 // Rust-101, Part 07: Operator Overloading, Tests, Formatting
2 // ==========================================================
4 pub use part05::BigInt;
6 // With our new knowledge of lifetimes, we are now able to write down the desired type of `min`:
8 fn min<'a>(&'a self, other: &'a Self) -> &'a Self;
11 pub fn vec_min<T: Minimum>(v: &Vec<T>) -> Option<&T> {
12 let mut min: Option<&T> = None;
14 min = Some(match min {
22 // **Exercise 07.1**: For our `vec_min` to be usable with `BigInt`, you will have to provide an implementation of
23 // `Minimum`. You should be able to pretty much copy the code you wrote for exercise 06.1. You should *not*
24 // make any copies of `BigInt`!
25 impl Minimum for BigInt {
26 fn min<'a>(&'a self, other: &'a Self) -> &'a Self {
31 // ## Operator Overloading
33 impl PartialEq for BigInt {
35 fn eq(&self, other: &BigInt) -> bool {
36 debug_assert!(self.test_invariant() && other.test_invariant());
42 // Now we can compare `BigInt`s. Rust treats `PratialEq` special in that it is wired to the operator `==`:
43 fn compare_big_ints() {
44 let b1 = BigInt::new(13);
45 let b2 = BigInt::new(37);
46 println!("b1 == b1: {} ; b1 == b2: {}; b1 != b2: {}", b1 == b1, b1 == b2, b1 != b2);
50 // With our equality test written, we are now ready to write our first testcase.
51 // the `test` attribute. `assert!` is like `debug_assert!`, but does not get compiled away in a release build.
54 let b1 = BigInt::new(1);
55 let b2 = BigInt::new(42);
56 let b3 = BigInt::from_vec(vec![0, 1]);
60 // Now run `cargo test` to execute the test. If you implemented `min` correctly, it should all work!
64 // All formating is handled by [`std::fmt`](http://doc.rust-lang.org/std/fmt/index.html). I won't explain
65 // all the details, and refer you to the documentation instead.
68 impl fmt::Debug for BigInt {
69 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
74 // Now we are ready to use `assert_eq!` to test `vec_min`.
77 let b1 = BigInt::new(1);
78 let b2 = BigInt::new(42);
79 let b3 = BigInt::from_vec(vec![0, 1]);
81 let v1 = vec![b2.clone(), b1.clone(), b3.clone()];
82 let v2 = vec![b2.clone(), b3.clone()];
86 // **Exercise 07.1**: Add some more testcases. In particular, make sure you test the behavior of
87 // `vec_min` on an empty vector. Also add tests for `BigInt::from_vec` (in particular, removing
88 // trailing zeros). Finally, break one of your functions in a subtle way and watch the test fail.
90 // **Exercise 07.2**: Go back to your good ol' `SomethingOrNothing`, and implement `Display` for it. (This will,
91 // of course, need a `Display` bound on `T`.) Then you should be able to use them with `println!` just like you do
92 // with numbers, and get rid of the inherent functions to print `SomethingOrNothing<i32>` and `SomethingOrNothing<f32>`.