X-Git-Url: https://git.ralfj.de/rust-101.git/blobdiff_plain/63b7a79069a399c32d575bb71832fcad134117c9..683f369ba51d22cb8b89ab31f1b20c01c117361c:/src/part06.rs?ds=inline diff --git a/src/part06.rs b/src/part06.rs index 8f9a723..7113094 100644 --- a/src/part06.rs +++ b/src/part06.rs @@ -44,7 +44,7 @@ fn vec_min(v: &Vec) -> Option { //@ The answer is already hidden in the type of `vec_min`: `v` is just borrowed, but //@ the Option that it returns is *owned*. We can't just return one of the elements of `v`, //@ as that would mean that it is no longer in the vector! In our code, this comes up when we update -//@ the intermediate variable `min`, which also has type `Option`. If you replace get rid of the +//@ the intermediate variable `min`, which also has type `Option`. If you get rid of the //@ `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 `e` to `min`. But that's not allowed, since @@ -138,8 +138,8 @@ fn rust_foo(mut v: Vec) -> i32 { //@ When analyzing the code of `rust_foo`, Rust has to assign a lifetime to `first`. It will choose the scope //@ where `first` is valid, which is the entire rest of the function. Because `head` ties the lifetime of its //@ argument and return value together, this means that `&v` also has to borrow `v` for the entire duration of -//@ the function `rust_foo`. So when we try to borrow `v` exclusively for `push`, Rust complains that the two references (the one -//@ for `head`, and the one for `push`) overlap. Lucky us! Rust caught our mistake and made sure we don't crash the program. +//@ the function `rust_foo`. So when we try to create a unique reference to `v` for `push`, Rust complains that the two references (the one +//@ for `head`, and the one for `push`) overlap, so neither of them can be unique. Lucky us! Rust caught our mistake and made sure we don't crash the program. //@ //@ So, to sum this up: Lifetimes enable Rust to reason about *how long* a reference is valid, how long ownership has been borrowed. We can thus //@ safely write functions like `head`, that return references into data they got as argument, and make sure they @@ -148,4 +148,4 @@ fn rust_foo(mut v: Vec) -> i32 { //@ Most of the time, we don't have to explicitly add lifetimes to function types. This is thanks to *lifetime elision*, //@ where Rust will automatically insert lifetimes we did not specify, following some [simple, well-documented rules](https://doc.rust-lang.org/stable/book/lifetimes.html#lifetime-elision). -//@ [index](main.html) | [previous](part05.html) | [raw source](https://www.ralfj.de/git/rust-101.git/blob_plain/HEAD:/workspace/src/part06.rs) | [next](part07.html) +//@ [index](main.html) | [previous](part05.html) | [raw source](workspace/src/part06.rs) | [next](part07.html)