Skip to content

Commit 8e4d81a

Browse files
committed
Add a note about scoping differences between a[b] and *a.index(b)
1 parent 2da80cf commit 8e4d81a

1 file changed

Lines changed: 18 additions & 1 deletion

File tree

src/expressions/array-expr.md

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,22 @@ r[expr.array.index.array]
8484
[Array] and [slice]-typed values can be indexed by writing a square-bracket-enclosed expression of type `usize` (the index) after them. When the array is mutable, the resulting [memory location] can be assigned to.
8585

8686
r[expr.array.index.trait]
87-
For other types an index expression `a[b]` is equivalent to `*std::ops::Index::index(&a, b)`, or `*std::ops::IndexMut::index_mut(&mut a, b)` in a mutable place expression context. Just as with methods, Rust will also insert dereference operations on `a` repeatedly to find an implementation.
87+
For other types an index expression `a[b]` is equivalent to `*std::ops::Index::index(&a, b)`, or `*std::ops::IndexMut::index_mut(&mut a, b)` in a mutable place expression context, except that when the index expression undergoes [temporary lifetime extension], the indexed expression `a` also has its [temporary scope] extended. Just as with methods, Rust will also insert dereference operations on `a` repeatedly to find an implementation.
88+
89+
```rust
90+
// The temporary holding the result of `vec![()]` is extended to
91+
// live to the end of the block, so `x` may be used in subsequent
92+
// statements.
93+
let x = &vec![()][0];
94+
# x;
95+
```
96+
97+
```rust,compile_fail,E0716
98+
// The temporary holding the result of `vec![()]` is dropped at the
99+
// end of the statement, so it's an error to use `y` after.
100+
let y = &*std::ops::Index::index(&vec![()], 0); // ERROR
101+
# y;
102+
```
88103

89104
r[expr.array.index.zero-index]
90105
Indices are zero-based for arrays and slices.
@@ -127,3 +142,5 @@ The array index expression can be implemented for types other than arrays and sl
127142
[panic]: ../panic.md
128143
[path]: path-expr.md
129144
[slice]: ../types/slice.md
145+
[temporary lifetime extension]: destructors.scope.lifetime-extension
146+
[temporary scope]: destructors.scope.temporary

0 commit comments

Comments
 (0)