1 // Rust-101, Part 05: Clone
2 // ========================
7 pub data: Vec<u64>, // least significant digit first, no trailing zeros
10 // Now that we fixed the data representation, we can start implementing methods on it.
12 pub fn new(x: u64) -> Self {
20 pub fn test_invariant(&self) -> bool {
21 if self.data.len() == 0 {
28 // We can convert any vector of digits into a number, by removing trailing zeros. The `mut`
29 // declaration for `v` here is just like the one in `let mut ...`: We completely own `v`, but Rust
30 // still asks us to make our intention of modifying it explicit. This `mut` is *not* part of the
31 // type of `from_vec` - the caller has to give up ownership of `v` anyway, so they don't care anymore
34 // **Exercise 05.1**: Implement this function.
36 // *Hint*: You can use `pop` to remove the last element of a vector.
37 pub fn from_vec(mut v: Vec<u64>) -> Self {
44 let v = vec![0,1 << 16];
45 let b1 = BigInt::from_vec((&v).clone());
46 let b2 = BigInt::from_vec(v);
49 impl Clone for BigInt {
50 fn clone(&self) -> Self {
55 // We can also make the type `SomethingOrNothing<T>` implement `Clone`.
56 use part02::{SomethingOrNothing,Something,Nothing};
57 impl<T: Clone> Clone for SomethingOrNothing<T> {
58 fn clone(&self) -> Self {
63 // **Exercise 05.2**: Write some more functions on `BigInt`. What about a function that returns the number of
64 // digits? The number of non-zero digits? The smallest/largest digit? Of course, these should all take `self` as a shared reference (i.e., in borrowed form).
66 // ## Mutation + aliasing considered harmful (part 2)
71 fn work_on_variant(mut var: Variant, text: String) {
72 let mut ptr: &mut i32;
74 Variant::Number(ref mut n) => ptr = n,
75 Variant::Text(_) => return,
77 /* var = Variant::Text(text); */ /* BAD! */