X-Git-Url: https://git.ralfj.de/rust-101.git/blobdiff_plain/bbd22a3d23af1ea8186c7a3bf733a07ba1f8ff70..ab7f9b241429bd675b437d2437799de75d2f409b:/workspace/src/part05.rs?ds=inline diff --git a/workspace/src/part05.rs b/workspace/src/part05.rs deleted file mode 100644 index d3c9544..0000000 --- a/workspace/src/part05.rs +++ /dev/null @@ -1,78 +0,0 @@ -// Rust-101, Part 05: Clone -// ======================== - -// ## Big Numbers - -pub struct BigInt { - pub data: Vec, -} - -// Now that we fixed the data representation, we can start implementing methods on it. -impl BigInt { - pub fn new(x: u64) -> Self { - if x == 0 { - BigInt { data: vec![] } - } else { - unimplemented!() - } - } - - pub fn test_invariant(&self) -> bool { - if self.data.len() == 0 { - true - } else { - unimplemented!() - } - } - - // We can convert any vector of digits into a number, by removing trailing zeros. The `mut` - // declaration for `v` here is just like the one in `let mut ...`, it says that we will locally - // change the vector `v`. - // - // **Exercise 05.1**: Implement this function. - // - // *Hint*: You can use `pop()` to remove the last element of a vector. - pub fn from_vec(mut v: Vec) -> Self { - unimplemented!() - } -} - -// ## Cloning -fn clone_demo() { - let v = vec![0,1 << 16]; - let b1 = BigInt::from_vec((&v).clone()); - let b2 = BigInt::from_vec(v); -} - -impl Clone for BigInt { - fn clone(&self) -> Self { - unimplemented!() - } -} - -// We can also make the type `SomethingOrNothing` implement `Clone`. -use part02::{SomethingOrNothing,Something,Nothing}; -impl Clone for SomethingOrNothing { - fn clone(&self) -> Self { - unimplemented!() - } -} - -// **Exercise 05.2**: Write some more functions on `BigInt`. What about a function that returns the number of -// digits? The number of non-zero digits? The smallest/largest digit? - -// ## Mutation + aliasing considered harmful (part 2) -enum Variant { - Number(i32), - Text(String), -} -fn work_on_variant(mut var: Variant, text: String) { - let mut ptr: &mut i32; - match var { - Variant::Number(ref mut n) => ptr = n, - Variant::Text(_) => return, - } - /* var = Variant::Text(text); */ /* BAD! */ - *ptr = 1337; -} -