Skip to content

Commit 715f7c3

Browse files
Add a precision for references
1 parent 7132092 commit 715f7c3

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

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

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

0 commit comments

Comments
 (0)