X-Git-Url: https://git.ralfj.de/rust-101.git/blobdiff_plain/b60c82e9d3b03aa36484c1ff68f34f4e78862d46..b89eed2cb450e67dd00102d1018adbb9a0cb1cae:/src/part05.rs diff --git a/src/part05.rs b/src/part05.rs index b593360..a0eb1d1 100644 --- a/src/part05.rs +++ b/src/part05.rs @@ -48,8 +48,10 @@ impl BigInt { } // 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`. + // 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. // @@ -60,8 +62,8 @@ impl BigInt { } // ## Cloning -//@ If you have a close look at the type of `BigInt::from_vec`, you will notice that it -//@ consumes the vector `v`. The caller hence loses access to its vector. There is however something +//@ If you take a close look at the type of `BigInt::from_vec`, you will notice that it +//@ consumes the vector `v`. The caller hence loses access to its vector. However, there is something //@ we can do if we don't want that to happen: We can explicitly `clone` the vector, //@ which means that a full (or *deep*) copy will be performed. Technically, //@ `clone` takes a borrowed vector, and returns a fully owned one. @@ -97,7 +99,7 @@ impl Clone for SomethingOrNothing { match *self { /*@*/ Nothing => Nothing, /*@*/ //@ In the second arm of the match, we need to talk about the value `v` - //@ that's stored in `self`. However, if we would write the pattern as + //@ that's stored in `self`. However, if we were to write the pattern as //@ `Something(v)`, that would indicate that we *own* `v` in the code //@ after the arrow. That can't work though, we have to leave `v` owned by //@ whoever called us - after all, we don't even own `self`, we just borrowed it. @@ -145,4 +147,4 @@ fn work_on_variant(mut var: Variant, text: String) { //@ I hope this example clarifies why Rust has to rule out mutation in the presence of aliasing *in general*, //@ not just for the specific case of a buffer being reallocated, and old pointers becoming hence invalid. -//@ [index](main.html) | [previous](part04.html) | [next](part06.html) +//@ [index](main.html) | [previous](part04.html) | [raw source](https://www.ralfj.de/git/rust-101.git/blob_plain/HEAD:/workspace/src/part05.rs) | [next](part06.html)