Skip to content

Commit ba8eb58

Browse files
committed
Rollup merge of rust-lang#25222 - GuillaumeGomez:doc-ref, r=steveklabnik
r? @steveklabnik
2 parents a725378 + 25543f3 commit ba8eb58

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/doc/trpl/references-and-borrowing.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,7 @@ println!("{}", y);
312312

313313
We get this error:
314314

315+
```text
315316
error: `x` does not live long enough
316317
y = &x;
317318
^
@@ -334,3 +335,37 @@ In other words, `y` is only valid for the scope where `x` exists. As soon as
334335
`x` goes away, it becomes invalid to refer to it. As such, the error says that
335336
the borrow ‘doesn’t live long enough’ because it’s not valid for the right
336337
amount of time.
338+
339+
The same problem occurs when the reference is declared _before_ the variable it refers to:
340+
341+
```rust,ignore
342+
let y: &i32;
343+
let x = 5;
344+
y = &x;
345+
346+
println!("{}", y);
347+
```
348+
349+
We get this error:
350+
351+
```text
352+
error: `x` does not live long enough
353+
y = &x;
354+
^
355+
note: reference must be valid for the block suffix following statement 0 at
356+
2:16...
357+
let y: &i32;
358+
let x = 5;
359+
y = &x;
360+
361+
println!("{}", y);
362+
}
363+
364+
note: ...but borrowed value is only valid for the block suffix following
365+
statement 1 at 3:14
366+
let x = 5;
367+
y = &x;
368+
369+
println!("{}", y);
370+
}
371+
```

0 commit comments

Comments
 (0)