|
| 1 | +// Sometimes, we have structs which hold on to data temporarily. A use-case of |
| 2 | +// this could be a routing component which accepts a connection and returns it to |
| 3 | +// another recipient. To avoid copying the data, we just accept a reference with |
| 4 | +// lifetime and return this reference later. |
| 5 | +// |
| 6 | +// In the example below, we create a `Router` instance in a limited scope. It |
| 7 | +// accepts a connection reference created in the enclosing scope and returns it. |
| 8 | +// In theory, this should be possible given that the connection reference outlives |
| 9 | +// the scope from which it is returned. However, the borrow checker does not |
| 10 | +// seem to understand it. What can we do about that? |
| 11 | + |
| 12 | +struct Router<'a> { |
| 13 | + connection: Option<&'a u64>, |
| 14 | + // ^^ lifetime of the connection reference |
| 15 | + // which may outlive the `Router` itself |
| 16 | +} |
| 17 | + |
| 18 | +impl<'a> Router<'a> { |
| 19 | + fn new() -> Self { |
| 20 | + Self { connection: None } |
| 21 | + } |
| 22 | + |
| 23 | + fn accept_connection(&mut self, connection: &'a u64) { |
| 24 | + self.connection = Some(connection); |
| 25 | + } |
| 26 | + |
| 27 | + fn return_connection(&mut self) -> Option<&'a u64> { |
| 28 | + // added lifetime annotation ^^ |
| 29 | + // |
| 30 | + // Without annotation, the compiler infers the output reference |
| 31 | + // to have the lifetime of the only input reference |
| 32 | + // -> the lifetime of `&mut self`. |
| 33 | + self.connection.take() |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +fn main() { |
| 38 | + let connection = &123; |
| 39 | + |
| 40 | + let returned_connection = { |
| 41 | + // Create router within scope |
| 42 | + let mut router = Router::new(); |
| 43 | + |
| 44 | + // Accept connection which lives longer than the router |
| 45 | + router.accept_connection(connection); |
| 46 | + |
| 47 | + // Return connection which **should** live longer than the router |
| 48 | + router.return_connection() |
| 49 | + // ^^^^^^^^^^^^^^^^^^^^ |
| 50 | + // |
| 51 | + // Without the explicit lifetime annotation in `return_connection`, |
| 52 | + // the reference from `return_connection` has the lifetime of `router`. |
| 53 | + // We are returning the reference from the scope, requiring it to outlive it, |
| 54 | + // so the compiler complains about `router` not living long enough. |
| 55 | + }; |
| 56 | + |
| 57 | + if let Some(connection) = returned_connection { |
| 58 | + println!("The connection is {connection}"); |
| 59 | + } |
| 60 | +} |
0 commit comments