You've already forked comprehensive-rust
mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-11-25 07:34:56 +02:00
Minor fixes in new lifetimes section (#2965)
@gribozavr I had a couple more fixes for https://github.com/google/comprehensive-rust/pull/2964 that I didn't push until after you merged the branch.
This commit is contained in:
@@ -8,7 +8,7 @@ In this case, we have a function where either `a` or `b` may be returned. In
|
||||
this case we use the lifetime annotations to tell the compiler that both borrows
|
||||
may flow into the return value.
|
||||
|
||||
```rust
|
||||
```rust,editable
|
||||
fn pick<'a>(c: bool, a: &'a i32, b: &'a i32) -> &'a i32 {
|
||||
if c { a } else { b }
|
||||
}
|
||||
|
||||
@@ -68,10 +68,16 @@ fn main() {
|
||||
enforcing that the function adheres to the contract set by the function's
|
||||
signature.
|
||||
|
||||
- The "help" note in the error notes that we can add a lifetime bound `'b: 'a`
|
||||
to say that `'b` will live at least as long as `'a`, which would then allow us
|
||||
to return `query`. On the next slide we'll talk about lifetime variance, which
|
||||
is the rule that allows us to return a longer lifetime when a shorter one is
|
||||
expected.
|
||||
# More to Explore
|
||||
|
||||
- The "help" message in the error notes that we can add a lifetime bound
|
||||
`'b: 'a` to say that `'b` will live at least as long as `'a`, which would then
|
||||
allow us to return `query`. This is an example of lifetime subtyping, which
|
||||
allows us to return a longer lifetime where a shorter one is expected.
|
||||
|
||||
- We can do something similar by returning a `'static` lifetime, e.g., a
|
||||
reference to a `static` variable. The `'static` lifetime is guaranteed to be
|
||||
longer than any other lifetime, so it's always safe to return in place of a
|
||||
shorter lifetime.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
minutes: 5
|
||||
---
|
||||
|
||||
# Lifetimes in Function Calls
|
||||
# Lifetime Elision
|
||||
|
||||
Lifetimes for function arguments and return values must be fully specified, but
|
||||
Rust allows lifetimes to be elided in most cases with
|
||||
|
||||
@@ -7,7 +7,7 @@ minutes: 5
|
||||
But what about when there are multiple borrows passed into a function and one
|
||||
being returned?
|
||||
|
||||
```rust,editable,ignore
|
||||
```rust,editable,compile_fail
|
||||
fn multiple(a: &i32, b: &i32) -> &i32 {
|
||||
todo!("Return either `a` or `b`")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user