X-Git-Url: https://git.ralfj.de/rust-101.git/blobdiff_plain/83e8dbfff2a6fdce785af58dbb13f007c4234cf2..ab7f9b241429bd675b437d2437799de75d2f409b:/workspace/src/part05.rs diff --git a/workspace/src/part05.rs b/workspace/src/part05.rs deleted file mode 100644 index 65f6f7d..0000000 --- a/workspace/src/part05.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Rust-101, Part 05: Clone -// ======================== - -// ## Big Numbers - -pub struct BigInt { - pub data: Vec, // least significant digit first, no trailing zeros -} - -// 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 { - unimplemented!() - } 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 ...`: We completely own `v`, but Rust - // still asks us to make our intention of modifying it explicit. This `mut` is *not* part of the - // type of `from_vec` - the caller has to give up ownership of `v` anyway, so they don't care anymore - // what you do to it. - // - // **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? Of course, these should all just borrow `self`. - -// ## 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; -} -