|
| 1 | +- Start Date: 2014-05-04 |
| 2 | +- RFC PR #: (leave this empty) |
| 3 | +- Rust Issue #: (leave this empty) |
| 4 | + |
| 5 | +# Summary |
| 6 | + |
| 7 | +Temporaries live for the enclosing block when found in a let-binding. This only |
| 8 | +holds when the reference to the temporary is taken directly. This logic should |
| 9 | +be extended to extend the cleanup scope of any temporary whose lifetime ends up |
| 10 | +in the let-binding. |
| 11 | + |
| 12 | +For example, the following doesn't work now, but should: |
| 13 | + |
| 14 | +```rust |
| 15 | +use std::os; |
| 16 | + |
| 17 | +fn main() { |
| 18 | + let x = os::args().slice_from(1); |
| 19 | + println!("{}", x); |
| 20 | +} |
| 21 | +``` |
| 22 | + |
| 23 | +# Motivation |
| 24 | + |
| 25 | +Temporary lifetimes are a bit confusing right now. Sometimes you can keep |
| 26 | +references to them, and sometimes you get the dreaded "borrowed value does not |
| 27 | +live long enough" error. Sometimes one operation works but an equivalent |
| 28 | +operation errors, e.g. autoref of `~[T]` to `&[T]` works but calling |
| 29 | +`.as_slice()` doesn't. In general it feels as though the compiler is simply |
| 30 | +being overly restrictive when it decides the temporary doesn't live long |
| 31 | +enough. |
| 32 | + |
| 33 | +# Drawbacks |
| 34 | + |
| 35 | +I can't think of any drawbacks. |
| 36 | + |
| 37 | +# Detailed design |
| 38 | + |
| 39 | +When a reference to a temporary is passed to a function (either as a regular |
| 40 | +argument or as the `self` argument of a method), and the function returns a |
| 41 | +value with the same lifetime as the temporary reference, the lifetime of the |
| 42 | +temporary should be extended the same way it would if the function was not |
| 43 | +invoked. |
| 44 | + |
| 45 | +For example, `~[T].as_slice()` takes `&'a self` and returns `&'a [T]`. Calling |
| 46 | +`as_slice()` on a temporary of type `~[T]` will implicitly take a reference |
| 47 | +`&'a ~[T]` and return a value `&'a [T]` This return value should be considered |
| 48 | +to extend the lifetime of the `~[T]` temporary just as taking an explicit |
| 49 | +reference (and skipping the method call) would. |
| 50 | + |
| 51 | +# Alternatives |
| 52 | + |
| 53 | +Don't do this. We live with the surprising borrowck errors and the ugly workarounds that look like |
| 54 | + |
| 55 | +```rust |
| 56 | +let x = os::args(); |
| 57 | +let x = x.slice_from(1); |
| 58 | +``` |
| 59 | + |
| 60 | +# Unresolved questions |
| 61 | + |
| 62 | +None that I know of. |
0 commit comments