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