X-Git-Url: https://git.ralfj.de/rust-101.git/blobdiff_plain/c25f3400060ea1a02f8fa9de69c39fd7b020e8a5..126f7bfe68883e6465d42c529b00d797b2f8478a:/src/part06.rs?ds=inline diff --git a/src/part06.rs b/src/part06.rs index b39a441..6d50c2d 100644 --- a/src/part06.rs +++ b/src/part06.rs @@ -26,9 +26,9 @@ impl BigInt { } // Now we can write `vec_min`. -//@ However, in order to make it type-check, we have to make a full (deep) copy of e by calling `clone()`. fn vec_min(v: &Vec) -> Option { let mut min: Option = None; + // If `v` is a shared borrowed vector, then the default for iterating over it is to call `iter`, the iterator that borrows the elements. for e in v { let e = e.clone(); /*@*/ min = Some(match min { /*@*/ @@ -38,7 +38,7 @@ fn vec_min(v: &Vec) -> Option { } min } -//@ Now, what's happening here? Why do we have to clone `e`, and why did we not +//@ Now, what's happening here? Why do we have to to make a full (deep) copy of `e`, and why did we not //@ have to do that in our previous version? //@ //@ The answer is already hidden in the type of `vec_min`: `v` is just borrowed, but @@ -48,7 +48,7 @@ fn vec_min(v: &Vec) -> Option { //@ `e.clone()`, Rust will complain "Cannot move out of borrowed content". That's because //@ `e` is a `&BigInt`. Assigning `min = Some(*e)` works just like a function call: Ownership of the //@ underlying data is transferred from where `e` borrows from to `min`. But that's not allowed, since -//@ we just borrowed `e`, so we cannot empty it! We can, however, call `clone()` on it. Then we own +//@ we just borrowed `e`, so we cannot empty it! We can, however, call `clone` on it. Then we own //@ the copy that was created, and hence we can store it in `min`.
//@ Of course, making such a full copy is expensive, so we'd like to avoid it. We'll some to that in the next part. @@ -92,7 +92,7 @@ impl Copy for SomethingOrNothing {} //@ `Clone`. This makes the cost explicit. // ## Lifetimes -//@ To fix the performance problems of `vec_min`, we need to avoid using `clone()`. We'd like +//@ To fix the performance problems of `vec_min`, we need to avoid using `clone`. We'd like //@ the return value to not be owned (remember that this was the source of our need for cloning), but *borrowed*. //@ The function `head` demonstrates how that could work: It borrows the first element of a vector if it is non-empty.