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;
19 // **Exercise 07.1**: For our `vec_min` to be usable with `BigInt`, you will have to provide an implementation of
20 // `Minimum`. You should be able to pretty much copy the code you wrote for exercise 06.1. You should *not*
22 impl Minimum for BigInt {
23 fn min<'a>(&'a self, other: &'a Self) -> &'a Self {
28 // ## Operator Overloading
30 impl PartialEq for BigInt {
32 fn eq(&self, other: &BigInt) -> bool {
33 debug_assert!(self.test_invariant() && other.test_invariant());
39 // Now we can compare `BigInt`s. Rust treats `PratialEq` special in that it is wired to the operator `==`:
40 fn compare_big_ints() {
41 let b1 = BigInt::new(13);
42 let b2 = BigInt::new(37);
43 println!("b1 == b1: {} ; b1 == b2: {}; b1 != b2: {}", b1 == b1, b1 == b2, b1 != b2);
47 // With our equality test written, we are now ready to write our first testcase.
48 // the `test` attribute. `assert!` is like `debug_assert!`, but does not get compiled away in a release build.
51 let b1 = BigInt::new(1);
52 let b2 = BigInt::new(42);
53 let b3 = BigInt::from_vec(vec![0, 1]);
57 // Now run `cargo test` to execute the test. If you implemented `min` correctly, it should all work!
61 // All formating is handled by [`std::fmt`](http://doc.rust-lang.org/std/fmt/index.html). I won't explain
62 // all the details, and refer you to the documentation instead.
65 impl fmt::Debug for BigInt {
66 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
71 // Now we are ready to use `assert_eq!` to test `vec_min`.
74 let b1 = BigInt::new(1);
75 let b2 = BigInt::new(42);
76 let b3 = BigInt::from_vec(vec![0, 1]);
78 let v1 = vec![b2.clone(), b1.clone(), b3.clone()];
79 let v2 = vec![b2.clone(), b3.clone()];
83 // **Exercise 07.1**: Add some more testcases. In particular, make sure you test the behavior of
84 // `vec_min` on an empty vector. Also add tests for `BigInt::from_vec` (in particular, removing
85 // trailing zeros). Finally, break one of your functions in a subtle way and watch the test fail.
87 // **Exercise 07.2**: Go back to your good ol' `SomethingOrNothing`, and implement `Display` for it. (This will,
88 // of course, need a `Display` bound on `T`.) Then you should be able to use them with `println!` just like you do
89 // with numbers, and get rid of the inherent functions to print `SomethingOrNothing<i32>` and `SomethingOrNothing<f32>`.