1 // Rust-101, Part 05: Clone
2 // ========================
10 // Now that we fixed the data representation, we can start implementing methods on it.
12 pub fn new(x: u64) -> Self {
14 BigInt { data: vec![] }
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 ...`, it says that we will locally
30 // change the vector `v`.
32 // **Exercise 05.1**: Implement this function.
34 // *Hint*: You can use `pop()` to remove the last element of a vector.
35 pub fn from_vec(mut v: Vec<u64>) -> Self {
42 let v = vec![0,1 << 16];
43 let b1 = BigInt::from_vec((&v).clone());
44 let b2 = BigInt::from_vec(v);
47 impl Clone for BigInt {
48 fn clone(&self) -> Self {
53 // We can also make the type `SomethingOrNothing<T>` implement `Clone`.
54 use part02::{SomethingOrNothing,Something,Nothing};
55 impl<T: Clone> Clone for SomethingOrNothing<T> {
56 fn clone(&self) -> Self {
61 // **Exercise 05.2**: Write some more functions on `BigInt`. What about a function that returns the number of
62 // digits? The number of non-zero digits? The smallest/largest digit?
64 // ## Mutation + aliasing considered harmful (part 2)
69 fn work_on_variant(mut var: Variant, text: String) {
70 let mut ptr: &mut i32;
72 Variant::Number(ref mut n) => ptr = n,
73 Variant::Text(_) => return,
75 /* var = Variant::Text(text); */ /* BAD! */