1 syntax::register_diagnostics! {
5 #### Note: this error code is no longer emitted by the compiler.
7 This error suggests that the expression arm corresponding to the noted pattern
8 will never be reached as for all possible values of the expression being
9 matched, one of the preceding patterns will match.
11 This means that perhaps some of the preceding patterns are too general, this
12 one is too specific or the ordering is incorrect.
14 For example, the following `match` block has too many arms:
18 Some(bar) => {/* ... */}
19 x => {/* ... */} // This handles the `None` case
20 _ => {/* ... */} // All possible cases have already been handled
24 `match` blocks have their patterns matched in order, so, for example, putting
25 a wildcard arm above a more specific arm will make the latter arm irrelevant.
27 Ensure the ordering of the match arm is correct and remove any superfluous
32 #### Note: this error code is no longer emitted by the compiler.
34 This error indicates that an empty match expression is invalid because the type
35 it is matching on is non-empty (there exist values of this type). In safe code
36 it is impossible to create an instance of an empty type, so empty match
37 expressions are almost never desired. This error is typically fixed by adding
38 one or more cases to the match expression.
40 An example of an empty type is `enum Empty { }`. So, the following will work:
55 fn foo(x: Option<String>) {
64 This error indicates that the compiler cannot guarantee a matching pattern for
65 one or more possible inputs to a match expression. Guaranteed matches are
66 required in order to assign values to match expressions, or alternatively,
67 determine the flow of execution.
69 Erroneous code example:
77 let x = Terminator::HastaLaVistaBaby;
79 match x { // error: non-exhaustive patterns: `HastaLaVistaBaby` not covered
80 Terminator::TalkToMyHand => {}
84 If you encounter this error you must alter your patterns so that every possible
85 value of the input type is matched. For types with a small number of variants
86 (like enums) you should probably cover all cases explicitly. Alternatively, the
87 underscore `_` wildcard pattern can be added after all other patterns to match
88 "anything else". Example:
96 let x = Terminator::HastaLaVistaBaby;
99 Terminator::TalkToMyHand => {}
100 Terminator::HastaLaVistaBaby => {}
106 Terminator::TalkToMyHand => {}
113 Patterns used to bind names must be irrefutable, that is, they must guarantee
114 that a name will be extracted in all cases.
116 Erroneous code example:
118 ```compile_fail,E0005
121 // error: refutable pattern in local binding: `None` not covered
124 If you encounter this error you probably need to use a `match` or `if let` to
125 deal with the possibility of failure. Example:
146 This error indicates that the bindings in a match arm would require a value to
147 be moved into more than one location, thus violating unique ownership. Code
148 like the following is invalid as it requires the entire `Option<String>` to be
149 moved into a variable called `op_string` while simultaneously requiring the
150 inner `String` to be moved into a variable called `s`.
152 Erroneous code example:
154 ```compile_fail,E0007
155 let x = Some("s".to_string());
158 op_string @ Some(s) => {}, // error: cannot bind by-move with sub-bindings
163 See also the error E0303.
167 In a pattern, all values that don't implement the `Copy` trait have to be bound
168 the same way. The goal here is to avoid binding simultaneously by-move and
171 This limitation may be removed in a future version of Rust.
173 Erroneous code example:
175 ```compile_fail,E0009
178 let x = Some((X { x: () }, X { x: () }));
180 Some((y, ref z)) => {}, // error: cannot bind by-move and by-ref in the
186 You have two solutions:
188 Solution #1: Bind the pattern's values the same way.
193 let x = Some((X { x: () }, X { x: () }));
195 Some((ref y, ref z)) => {},
196 // or Some((y, z)) => {}
201 Solution #2: Implement the `Copy` trait for the `X` structure.
203 However, please keep in mind that the first solution should be preferred.
206 #[derive(Clone, Copy)]
209 let x = Some((X { x: () }, X { x: () }));
211 Some((y, ref z)) => {},
218 The value of statics and constants must be known at compile time, and they live
219 for the entire lifetime of a program. Creating a boxed value allocates memory on
220 the heap at runtime, and therefore cannot be done at compile time.
222 Erroneous code example:
224 ```compile_fail,E0010
225 #![feature(box_syntax)]
227 const CON : Box<i32> = box 0;
232 Static and const variables can refer to other const variables. But a const
233 variable cannot refer to a static variable.
235 Erroneous code example:
237 ```compile_fail,E0013
242 In this example, `Y` cannot refer to `X` here. To fix this, the value can be
243 extracted as a const and then used:
252 // FIXME(#57563) Change the language here when const fn stabilizes
254 The only functions that can be called in static or constant expressions are
255 `const` functions, and struct/enum constructors. `const` functions are only
256 available on a nightly compiler. Rust currently does not support more general
257 compile-time function execution.
260 const FOO: Option<u8> = Some(1); // enum constructor
262 const BAR: Bar = Bar {x: 1}; // struct constructor
265 See [RFC 911] for more details on the design of `const fn`s.
267 [RFC 911]: https://github.com/rust-lang/rfcs/blob/master/text/0911-const-fn.md
271 References in statics and constants may only refer to immutable values.
273 Erroneous code example:
275 ```compile_fail,E0017
279 // these three are not allowed:
280 const CR: &mut i32 = &mut C;
281 static STATIC_REF: &'static mut i32 = &mut X;
282 static CONST_REF: &'static mut i32 = &mut C;
285 Statics are shared everywhere, and if they refer to mutable data one might
286 violate memory safety since holding multiple mutable references to shared data
289 If you really want global mutable state, try using `static mut` or a global
294 A function call isn't allowed in the const's initialization expression
295 because the expression's value must be known at compile-time.
297 Erroneous code example:
299 ```compile_fail,E0019
300 #![feature(box_syntax)]
305 static STATIC11: Box<MyOwned> = box MyOwned; // error!
309 Remember: you can't use a function call inside a const's initialization
310 expression! However, you can totally use it anywhere else:
318 fn func(&self) -> i32 {
324 const FOO: Test = Test::V1;
326 FOO.func(); // here is good
327 let x = FOO.func(); // or even here!
333 When matching against a range, the compiler verifies that the range is
334 non-empty. Range patterns include both end-points, so this is equivalent to
335 requiring the start of the range to be less than or equal to the end of the
338 Erroneous code example:
340 ```compile_fail,E0030
342 // This range is ok, albeit pointless.
344 // This range is empty, and the compiler can tell.
351 Unsafe code was used outside of an unsafe function or block.
353 Erroneous code example:
355 ```compile_fail,E0133
356 unsafe fn f() { return; } // This is the unsafe code
359 f(); // error: call to unsafe function requires unsafe function or block
363 Using unsafe functionality is potentially dangerous and disallowed by safety
366 * Dereferencing raw pointers
367 * Calling functions via FFI
368 * Calling functions marked unsafe
370 These safety checks can be relaxed for a section of the code by wrapping the
371 unsafe instructions with an `unsafe` block. For instance:
374 unsafe fn f() { return; }
377 unsafe { f(); } // ok!
381 See also https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html
385 An associated const has been referenced in a pattern.
387 Erroneous code example:
389 ```compile_fail,E0158
390 enum EFoo { A, B, C, D }
396 fn test<A: Foo>(arg: EFoo) {
405 `const` and `static` mean different things. A `const` is a compile-time
406 constant, an alias for a literal value. This property means you can match it
407 directly within a pattern.
409 The `static` keyword, on the other hand, guarantees a fixed location in memory.
410 This does not always mean that the value is constant. For example, a global
411 mutex can be declared `static` as well.
413 If you want to match against a `static`, consider using a guard instead:
416 static FORTY_TWO: i32 = 42;
419 Some(x) if x == FORTY_TWO => {}
426 A value was moved. However, its size was not known at compile time, and only
427 values of a known size can be moved.
429 Erroneous code example:
431 ```compile_fail,E0161
432 #![feature(box_syntax)]
435 let array: &[isize] = &[1, 2, 3];
436 let _x: Box<[isize]> = box *array;
437 // error: cannot move a value of type [isize]: the size of [isize] cannot
438 // be statically determined
442 In Rust, you can only move a value when its size is known at compile time.
444 To work around this restriction, consider "hiding" the value behind a reference:
445 either `&x` or `&mut x`. Since a reference has a fixed size, this lets you move
446 it around as usual. Example:
449 #![feature(box_syntax)]
452 let array: &[isize] = &[1, 2, 3];
453 let _x: Box<&[isize]> = box array; // ok!
459 #### Note: this error code is no longer emitted by the compiler.
461 An if-let pattern attempts to match the pattern, and enters the body if the
462 match was successful. If the match is irrefutable (when it cannot fail to
463 match), use a regular `let`-binding instead. For instance:
466 struct Irrefutable(i32);
467 let irr = Irrefutable(0);
469 // This fails to compile because the match is irrefutable.
470 if let Irrefutable(x) = irr {
471 // This body will always be executed.
479 struct Irrefutable(i32);
480 let irr = Irrefutable(0);
482 let Irrefutable(x) = irr;
488 #### Note: this error code is no longer emitted by the compiler.
490 A while-let pattern attempts to match the pattern, and enters the body if the
491 match was successful. If the match is irrefutable (when it cannot fail to
492 match), use a regular `let`-binding inside a `loop` instead. For instance:
495 struct Irrefutable(i32);
496 let irr = Irrefutable(0);
498 // This fails to compile because the match is irrefutable.
499 while let Irrefutable(x) = irr {
507 struct Irrefutable(i32);
508 let irr = Irrefutable(0);
511 let Irrefutable(x) = irr;
518 Enum variants are qualified by default. For example, given this type:
527 You would match it using:
543 If you don't qualify the names, the code will bind new variables named "GET" and
544 "POST" instead. This behavior is likely not what you want, so `rustc` warns when
547 Qualified names are good practice, and most code works well with them. But if
548 you prefer them unqualified, you can import the variants into scope:
552 enum Method { GET, POST }
556 If you want others to be able to import variants from your module directly, use
561 pub enum Method { GET, POST }
568 #### Note: this error code is no longer emitted by the compiler.
570 Patterns used to bind names must be irrefutable. That is, they must guarantee
571 that a name will be extracted in all cases. Instead of pattern matching the
572 loop variable, consider using a `match` or `if let` inside the loop body. For
575 ```compile_fail,E0005
576 let xs : Vec<Option<i32>> = vec![Some(1), None];
578 // This fails because `None` is not covered.
584 Match inside the loop instead:
587 let xs : Vec<Option<i32>> = vec![Some(1), None];
600 let xs : Vec<Option<i32>> = vec![Some(1), None];
603 if let Some(x) = item {
611 #### Note: this error code is no longer emitted by the compiler.
613 Mutable borrows are not allowed in pattern guards, because matching cannot have
614 side effects. Side effects could alter the matched object or the environment
615 on which the match depends in such a way, that the match would not be
616 exhaustive. For instance, the following would not match any arm if mutable
617 borrows were allowed:
619 ```compile_fail,E0596
622 option if option.take().is_none() => {
623 /* impossible, option is `Some` */
625 Some(_) => { } // When the previous match failed, the option became `None`.
631 #### Note: this error code is no longer emitted by the compiler.
633 Assignments are not allowed in pattern guards, because matching cannot have
634 side effects. Side effects could alter the matched object or the environment
635 on which the match depends in such a way, that the match would not be
636 exhaustive. For instance, the following would not match any arm if assignments
639 ```compile_fail,E0594
642 option if { option = None; false } => { },
643 Some(_) => { } // When the previous match failed, the option became `None`.
649 In certain cases it is possible for sub-bindings to violate memory safety.
650 Updates to the borrow checker in a future version of Rust may remove this
651 restriction, but for now patterns must be rewritten without sub-bindings.
655 ```compile_fail,E0303
656 match Some("hi".to_string()) {
657 ref op_string_ref @ Some(s) => {},
665 match Some("hi".to_string()) {
667 let op_string_ref = &Some(s);
674 The `op_string_ref` binding has type `&Option<&String>` in both cases.
676 See also https://github.com/rust-lang/rust/issues/14587
680 This error occurs when an attempt is made to use data captured by a closure,
681 when that data may no longer exist. It's most commonly seen when attempting to
684 ```compile_fail,E0373
685 fn foo() -> Box<Fn(u32) -> u32> {
691 Notice that `x` is stack-allocated by `foo()`. By default, Rust captures
692 closed-over data by reference. This means that once `foo()` returns, `x` no
693 longer exists. An attempt to access `x` within the closure would thus be
696 Another situation where this might be encountered is when spawning threads:
698 ```compile_fail,E0373
703 let thr = std::thread::spawn(|| {
709 Since our new thread runs in parallel, the stack frame containing `x` and `y`
710 may well have disappeared by the time we try to use them. Even if we call
711 `thr.join()` within foo (which blocks until `thr` has completed, ensuring the
712 stack frame won't disappear), we will not succeed: the compiler cannot prove
713 that this behaviour is safe, and so won't let us do it.
715 The solution to this problem is usually to switch to using a `move` closure.
716 This approach moves (or copies, where possible) data into the closure, rather
717 than taking references to it. For example:
720 fn foo() -> Box<Fn(u32) -> u32> {
722 Box::new(move |y| x + y)
726 Now that the closure has its own copy of the data, there's no need to worry
731 It is not allowed to use or capture an uninitialized variable.
733 Erroneous code example:
735 ```compile_fail,E0381
738 let y = x; // error, use of possibly-uninitialized variable
742 To fix this, ensure that any declared variables are initialized before being
754 This error occurs when an attempt is made to use a variable after its contents
755 have been moved elsewhere.
757 Erroneous code example:
759 ```compile_fail,E0382
760 struct MyStruct { s: u32 }
763 let mut x = MyStruct{ s: 5u32 };
770 Since `MyStruct` is a type that is not marked `Copy`, the data gets moved out
771 of `x` when we set `y`. This is fundamental to Rust's ownership system: outside
772 of workarounds like `Rc`, a value cannot be owned by more than one variable.
774 Sometimes we don't need to move the value. Using a reference, we can let another
775 function borrow the value without changing its ownership. In the example below,
776 we don't actually have to move our string to `calculate_length`, we can give it
777 a reference to it with `&` instead.
781 let s1 = String::from("hello");
783 let len = calculate_length(&s1);
785 println!("The length of '{}' is {}.", s1, len);
788 fn calculate_length(s: &String) -> usize {
793 A mutable reference can be created with `&mut`.
795 Sometimes we don't want a reference, but a duplicate. All types marked `Clone`
796 can be duplicated by calling `.clone()`. Subsequent changes to a clone do not
797 affect the original variable.
799 Most types in the standard library are marked `Clone`. The example below
800 demonstrates using `clone()` on a string. `s1` is first set to "many", and then
801 copied to `s2`. Then the first character of `s1` is removed, without affecting
802 `s2`. "any many" is printed to the console.
806 let mut s1 = String::from("many");
809 println!("{} {}", s1, s2);
813 If we control the definition of a type, we can implement `Clone` on it ourselves
814 with `#[derive(Clone)]`.
816 Some types have no ownership semantics at all and are trivial to duplicate. An
817 example is `i32` and the other number types. We don't have to call `.clone()` to
818 clone them, because they are marked `Copy` in addition to `Clone`. Implicit
819 cloning is more convenient in this case. We can mark our own types `Copy` if
820 all their members also are marked `Copy`.
822 In the example below, we implement a `Point` type. Because it only stores two
823 integers, we opt-out of ownership semantics with `Copy`. Then we can
824 `let p2 = p1` without `p1` being moved.
827 #[derive(Copy, Clone)]
828 struct Point { x: i32, y: i32 }
831 let mut p1 = Point{ x: -1, y: 2 };
834 println!("p1: {}, {}", p1.x, p1.y);
835 println!("p2: {}, {}", p2.x, p2.y);
839 Alternatively, if we don't control the struct's definition, or mutable shared
840 ownership is truly required, we can use `Rc` and `RefCell`:
843 use std::cell::RefCell;
846 struct MyStruct { s: u32 }
849 let mut x = Rc::new(RefCell::new(MyStruct{ s: 5u32 }));
851 x.borrow_mut().s = 6;
852 println!("{}", x.borrow().s);
856 With this approach, x and y share ownership of the data via the `Rc` (reference
857 count type). `RefCell` essentially performs runtime borrow checking: ensuring
858 that at most one writer or multiple readers can access the data at any one time.
860 If you wish to learn more about ownership in Rust, start with the chapter in the
863 https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html
867 #### Note: this error code is no longer emitted by the compiler.
869 This error occurs when an attempt is made to partially reinitialize a
870 structure that is currently uninitialized.
872 For example, this can happen when a drop has taken place:
879 fn drop(&mut self) { /* ... */ }
882 let mut x = Foo { a: 1 };
883 drop(x); // `x` is now uninitialized
884 x.a = 2; // error, partial reinitialization of uninitialized structure `t`
887 This error can be fixed by fully reinitializing the structure in question:
894 fn drop(&mut self) { /* ... */ }
897 let mut x = Foo { a: 1 };
904 This error occurs when an attempt is made to reassign an immutable variable.
906 Erroneous code example:
908 ```compile_fail,E0384
911 x = 5; // error, reassignment of immutable variable
915 By default, variables in Rust are immutable. To fix this error, add the keyword
916 `mut` after the keyword `let` when declaring the variable. For example:
927 #### Note: this error code is no longer emitted by the compiler.
929 This error occurs when an attempt is made to mutate the target of a mutable
930 reference stored inside an immutable container.
932 For example, this can happen when storing a `&mut` inside an immutable `Box`:
936 let y: Box<_> = Box::new(&mut x);
937 **y = 2; // error, cannot assign to data in an immutable container
940 This error can be fixed by making the container mutable:
944 let mut y: Box<_> = Box::new(&mut x);
948 It can also be fixed by using a type with interior mutability, such as `Cell`
955 let y: Box<Cell<_>> = Box::new(Cell::new(x));
961 #### Note: this error code is no longer emitted by the compiler.
963 This error occurs when an attempt is made to mutate or mutably reference data
964 that a closure has captured immutably.
966 Erroneous code example:
969 // Accepts a function or a closure that captures its environment immutably.
970 // Closures passed to foo will not be able to mutate their closed-over state.
971 fn foo<F: Fn()>(f: F) { }
973 // Attempts to mutate closed-over data. Error message reads:
974 // `cannot assign to data in a captured outer variable...`
980 // Attempts to take a mutable reference to closed-over data. Error message
981 // reads: `cannot borrow data mutably in a captured outer variable...`
984 foo(|| { let y = &mut x; });
988 The problem here is that foo is defined as accepting a parameter of type `Fn`.
989 Closures passed into foo will thus be inferred to be of type `Fn`, meaning that
990 they capture their context immutably.
992 If the definition of `foo` is under your control, the simplest solution is to
993 capture the data mutably. This can be done by defining `foo` to take FnMut
997 fn foo<F: FnMut()>(f: F) { }
1000 Alternatively, we can consider using the `Cell` and `RefCell` types to achieve
1001 interior mutability through a shared reference. Our example's `mutable`
1002 function could be redefined as below:
1005 use std::cell::Cell;
1007 fn foo<F: Fn()>(f: F) { }
1010 let x = Cell::new(0u32);
1015 You can read more about cell types in the API documentation:
1017 https://doc.rust-lang.org/std/cell/
1021 #### Note: this error code is no longer emitted by the compiler.
1025 #### Note: this error code is no longer emitted by the compiler.
1027 An attempt was made to mutate data using a non-mutable reference. This
1028 commonly occurs when attempting to assign to a non-mutable reference of a
1029 mutable reference (`&(&mut T)`).
1031 Erroneous code example:
1039 let mut fancy = FancyNum{ num: 5 };
1040 let fancy_ref = &(&mut fancy);
1041 fancy_ref.num = 6; // error: cannot assign to data in a `&` reference
1042 println!("{}", fancy_ref.num);
1046 Here, `&mut fancy` is mutable, but `&(&mut fancy)` is not. Creating an
1047 immutable reference to a value borrows it immutably. There can be multiple
1048 references of type `&(&mut T)` that point to the same value, so they must be
1049 immutable to prevent multiple mutable references to the same value.
1051 To fix this, either remove the outer reference:
1059 let mut fancy = FancyNum{ num: 5 };
1061 let fancy_ref = &mut fancy;
1062 // `fancy_ref` is now &mut FancyNum, rather than &(&mut FancyNum)
1064 fancy_ref.num = 6; // No error!
1066 println!("{}", fancy_ref.num);
1070 Or make the outer reference mutable:
1078 let mut fancy = FancyNum{ num: 5 };
1080 let fancy_ref = &mut (&mut fancy);
1081 // `fancy_ref` is now &mut(&mut FancyNum), rather than &(&mut FancyNum)
1083 fancy_ref.num = 6; // No error!
1085 println!("{}", fancy_ref.num);
1091 A borrow of a constant containing interior mutability was attempted.
1093 Erroneous code example:
1095 ```compile_fail,E0492
1096 use std::sync::atomic::AtomicUsize;
1098 const A: AtomicUsize = AtomicUsize::new(0);
1099 static B: &'static AtomicUsize = &A;
1100 // error: cannot borrow a constant which may contain interior mutability,
1101 // create a static instead
1104 A `const` represents a constant value that should never change. If one takes
1105 a `&` reference to the constant, then one is taking a pointer to some memory
1106 location containing the value. Normally this is perfectly fine: most values
1107 can't be changed via a shared `&` pointer, but interior mutability would allow
1108 it. That is, a constant value could be mutated. On the other hand, a `static` is
1109 explicitly a single memory location, which can be mutated at will.
1111 So, in order to solve this error, either use statics which are `Sync`:
1114 use std::sync::atomic::AtomicUsize;
1116 static A: AtomicUsize = AtomicUsize::new(0);
1117 static B: &'static AtomicUsize = &A; // ok!
1120 You can also have this error while using a cell type:
1122 ```compile_fail,E0492
1123 use std::cell::Cell;
1125 const A: Cell<usize> = Cell::new(1);
1126 const B: &Cell<usize> = &A;
1127 // error: cannot borrow a constant which may contain interior mutability,
1128 // create a static instead
1131 struct C { a: Cell<usize> }
1133 const D: C = C { a: Cell::new(1) };
1134 const E: &Cell<usize> = &D.a; // error
1137 const F: &C = &D; // error
1140 This is because cell types do operations that are not thread-safe. Due to this,
1141 they don't implement Sync and thus can't be placed in statics.
1143 However, if you still wish to use these types, you can achieve this by an unsafe
1147 use std::cell::Cell;
1148 use std::marker::Sync;
1150 struct NotThreadSafe<T> {
1154 unsafe impl<T> Sync for NotThreadSafe<T> {}
1156 static A: NotThreadSafe<usize> = NotThreadSafe { value : Cell::new(1) };
1157 static B: &'static NotThreadSafe<usize> = &A; // ok!
1160 Remember this solution is unsafe! You will have to ensure that accesses to the
1161 cell are synchronized.
1165 A type with a `Drop` implementation was destructured when trying to initialize
1168 Erroneous code example:
1170 ```compile_fail,E0493
1175 impl Drop for DropType {
1176 fn drop(&mut self) {}
1183 static FOO: Foo = Foo { ..Foo { field1: DropType::A } }; // error!
1186 The problem here is that if the given type or one of its fields implements the
1187 `Drop` trait, this `Drop` implementation cannot be called during the static
1188 type initialization which might cause a memory leak. To prevent this issue,
1189 you need to instantiate all the static type's fields by hand.
1196 impl Drop for DropType {
1197 fn drop(&mut self) {}
1204 static FOO: Foo = Foo { field1: DropType::A }; // We initialize all fields
1210 A variable was borrowed as mutable more than once.
1212 Erroneous code example:
1214 ```compile_fail,E0499
1219 // error: cannot borrow `i` as mutable more than once at a time
1222 Please note that in rust, you can either have many immutable references, or one
1223 mutable reference. Take a look at
1224 https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html for more
1225 information. Example:
1230 let mut x = &mut i; // ok!
1235 let b = &i; // still ok!
1236 let c = &i; // still ok!
1243 A borrowed variable was used by a closure.
1245 Erroneous code example:
1247 ```compile_fail,E0500
1248 fn you_know_nothing(jon_snow: &mut i32) {
1249 let nights_watch = &jon_snow;
1251 *jon_snow = 3; // error: closure requires unique access to `jon_snow`
1252 // but it is already borrowed
1254 println!("{}", nights_watch);
1258 In here, `jon_snow` is already borrowed by the `nights_watch` reference, so it
1259 cannot be borrowed by the `starks` closure at the same time. To fix this issue,
1260 you can create the closure after the borrow has ended:
1263 fn you_know_nothing(jon_snow: &mut i32) {
1264 let nights_watch = &jon_snow;
1265 println!("{}", nights_watch);
1272 Or, if the type implements the `Clone` trait, you can clone it between
1276 fn you_know_nothing(jon_snow: &mut i32) {
1277 let mut jon_copy = jon_snow.clone();
1281 println!("{}", jon_copy);
1287 This error indicates that a mutable variable is being used while it is still
1288 captured by a closure. Because the closure has borrowed the variable, it is not
1289 available for use until the closure goes out of scope.
1291 Note that a capture will either move or borrow a variable, but in this
1292 situation, the closure is borrowing the variable. Take a look at
1293 http://rustbyexample.com/fn/closures/capture.html for more information about
1296 Erroneous code example:
1298 ```compile_fail,E0501
1299 fn inside_closure(x: &mut i32) {
1300 // Actions which require unique access
1303 fn outside_closure(x: &mut i32) {
1304 // Actions which require unique access
1307 fn foo(a: &mut i32) {
1311 outside_closure(a); // error: cannot borrow `*a` as mutable because previous
1312 // closure requires unique access.
1317 To fix this error, you can finish using the closure before using the captured
1321 fn inside_closure(x: &mut i32) {}
1322 fn outside_closure(x: &mut i32) {}
1324 fn foo(a: &mut i32) {
1329 // borrow on `a` ends.
1330 outside_closure(a); // ok!
1334 Or you can pass the variable as a parameter to the closure:
1337 fn inside_closure(x: &mut i32) {}
1338 fn outside_closure(x: &mut i32) {}
1340 fn foo(a: &mut i32) {
1341 let mut bar = |s: &mut i32| {
1349 It may be possible to define the closure later:
1352 fn inside_closure(x: &mut i32) {}
1353 fn outside_closure(x: &mut i32) {}
1355 fn foo(a: &mut i32) {
1366 This error indicates that you are trying to borrow a variable as mutable when it
1367 has already been borrowed as immutable.
1369 Erroneous code example:
1371 ```compile_fail,E0502
1372 fn bar(x: &mut i32) {}
1373 fn foo(a: &mut i32) {
1374 let ref y = a; // a is borrowed as immutable.
1375 bar(a); // error: cannot borrow `*a` as mutable because `a` is also borrowed
1381 To fix this error, ensure that you don't have any other references to the
1382 variable before trying to access it mutably:
1385 fn bar(x: &mut i32) {}
1386 fn foo(a: &mut i32) {
1388 let ref y = a; // ok!
1393 For more information on the rust ownership system, take a look at
1394 https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html.
1398 A value was used after it was mutably borrowed.
1400 Erroneous code example:
1402 ```compile_fail,E0503
1405 // Create a mutable borrow of `value`.
1406 let borrow = &mut value;
1407 let _sum = value + 1; // error: cannot use `value` because
1408 // it was mutably borrowed
1409 println!("{}", borrow);
1413 In this example, `value` is mutably borrowed by `borrow` and cannot be
1414 used to calculate `sum`. This is not possible because this would violate
1415 Rust's mutability rules.
1417 You can fix this error by finishing using the borrow before the next use of
1423 let borrow = &mut value;
1424 println!("{}", borrow);
1425 // The block has ended and with it the borrow.
1426 // You can now use `value` again.
1427 let _sum = value + 1;
1431 Or by cloning `value` before borrowing it:
1436 // We clone `value`, creating a copy.
1437 let value_cloned = value.clone();
1438 // The mutable borrow is a reference to `value` and
1439 // not to `value_cloned`...
1440 let borrow = &mut value;
1441 // ... which means we can still use `value_cloned`,
1442 let _sum = value_cloned + 1;
1443 // even though the borrow only ends here.
1444 println!("{}", borrow);
1448 You can find more information about borrowing in the rust-book:
1449 http://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html
1453 #### Note: this error code is no longer emitted by the compiler.
1455 This error occurs when an attempt is made to move a borrowed variable into a
1458 Erroneous code example:
1466 let fancy_num = FancyNum { num: 5 };
1467 let fancy_ref = &fancy_num;
1470 println!("child function: {}", fancy_num.num);
1471 // error: cannot move `fancy_num` into closure because it is borrowed
1475 println!("main function: {}", fancy_ref.num);
1479 Here, `fancy_num` is borrowed by `fancy_ref` and so cannot be moved into
1480 the closure `x`. There is no way to move a value into a closure while it is
1481 borrowed, as that would invalidate the borrow.
1483 If the closure can't outlive the value being moved, try using a reference
1492 let fancy_num = FancyNum { num: 5 };
1493 let fancy_ref = &fancy_num;
1496 // fancy_ref is usable here because it doesn't move `fancy_num`
1497 println!("child function: {}", fancy_ref.num);
1502 println!("main function: {}", fancy_num.num);
1506 If the value has to be borrowed and then moved, try limiting the lifetime of
1507 the borrow using a scoped block:
1515 let fancy_num = FancyNum { num: 5 };
1518 let fancy_ref = &fancy_num;
1519 println!("main function: {}", fancy_ref.num);
1520 // `fancy_ref` goes out of scope here
1524 // `fancy_num` can be moved now (no more references exist)
1525 println!("child function: {}", fancy_num.num);
1532 If the lifetime of a reference isn't enough, such as in the case of threading,
1533 consider using an `Arc` to create a reference-counted value:
1544 let fancy_ref1 = Arc::new(FancyNum { num: 5 });
1545 let fancy_ref2 = fancy_ref1.clone();
1547 let x = thread::spawn(move || {
1548 // `fancy_ref1` can be moved and has a `'static` lifetime
1549 println!("child thread: {}", fancy_ref1.num);
1552 x.join().expect("child thread should finish");
1553 println!("main thread: {}", fancy_ref2.num);
1559 A value was moved out while it was still borrowed.
1561 Erroneous code example:
1563 ```compile_fail,E0505
1566 fn borrow(val: &Value) {}
1568 fn eat(val: Value) {}
1572 let _ref_to_val: &Value = &x;
1574 borrow(_ref_to_val);
1578 Here, the function `eat` takes ownership of `x`. However,
1579 `x` cannot be moved because the borrow to `_ref_to_val`
1580 needs to last till the function `borrow`.
1581 To fix that you can do a few different things:
1583 * Try to avoid moving the variable.
1584 * Release borrow before move.
1585 * Implement the `Copy` trait on the type.
1592 fn borrow(val: &Value) {}
1594 fn eat(val: &Value) {}
1599 let ref_to_val: &Value = &x;
1600 eat(&x); // pass by reference, if it's possible
1610 fn borrow(val: &Value) {}
1612 fn eat(val: Value) {}
1617 let ref_to_val: &Value = &x;
1619 // ref_to_val is no longer used.
1627 #[derive(Clone, Copy)] // implement Copy trait
1630 fn borrow(val: &Value) {}
1632 fn eat(val: Value) {}
1636 let ref_to_val: &Value = &x;
1637 eat(x); // it will be copied here.
1642 You can find more information about borrowing in the rust-book:
1643 http://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html
1647 This error occurs when an attempt is made to assign to a borrowed value.
1649 Erroneous code example:
1651 ```compile_fail,E0506
1657 let mut fancy_num = FancyNum { num: 5 };
1658 let fancy_ref = &fancy_num;
1659 fancy_num = FancyNum { num: 6 };
1660 // error: cannot assign to `fancy_num` because it is borrowed
1662 println!("Num: {}, Ref: {}", fancy_num.num, fancy_ref.num);
1666 Because `fancy_ref` still holds a reference to `fancy_num`, `fancy_num` can't
1667 be assigned to a new value as it would invalidate the reference.
1669 Alternatively, we can move out of `fancy_num` into a second `fancy_num`:
1677 let mut fancy_num = FancyNum { num: 5 };
1678 let moved_num = fancy_num;
1679 fancy_num = FancyNum { num: 6 };
1681 println!("Num: {}, Moved num: {}", fancy_num.num, moved_num.num);
1685 If the value has to be borrowed, try limiting the lifetime of the borrow using
1694 let mut fancy_num = FancyNum { num: 5 };
1697 let fancy_ref = &fancy_num;
1698 println!("Ref: {}", fancy_ref.num);
1701 // Works because `fancy_ref` is no longer in scope
1702 fancy_num = FancyNum { num: 6 };
1703 println!("Num: {}", fancy_num.num);
1707 Or by moving the reference into a function:
1715 let mut fancy_num = FancyNum { num: 5 };
1717 print_fancy_ref(&fancy_num);
1719 // Works because function borrow has ended
1720 fancy_num = FancyNum { num: 6 };
1721 println!("Num: {}", fancy_num.num);
1724 fn print_fancy_ref(fancy_ref: &FancyNum){
1725 println!("Ref: {}", fancy_ref.num);
1731 You tried to move out of a value which was borrowed.
1733 This can also happen when using a type implementing `Fn` or `FnMut`, as neither
1734 allows moving out of them (they usually represent closures which can be called
1735 more than once). Much of the text following applies equally well to non-`FnOnce`
1738 Erroneous code example:
1740 ```compile_fail,E0507
1741 use std::cell::RefCell;
1743 struct TheDarkKnight;
1745 impl TheDarkKnight {
1746 fn nothing_is_true(self) {}
1750 let x = RefCell::new(TheDarkKnight);
1752 x.borrow().nothing_is_true(); // error: cannot move out of borrowed content
1756 Here, the `nothing_is_true` method takes the ownership of `self`. However,
1757 `self` cannot be moved because `.borrow()` only provides an `&TheDarkKnight`,
1758 which is a borrow of the content owned by the `RefCell`. To fix this error,
1759 you have three choices:
1761 * Try to avoid moving the variable.
1762 * Somehow reclaim the ownership.
1763 * Implement the `Copy` trait on the type.
1768 use std::cell::RefCell;
1770 struct TheDarkKnight;
1772 impl TheDarkKnight {
1773 fn nothing_is_true(&self) {} // First case, we don't take ownership
1777 let x = RefCell::new(TheDarkKnight);
1779 x.borrow().nothing_is_true(); // ok!
1786 use std::cell::RefCell;
1788 struct TheDarkKnight;
1790 impl TheDarkKnight {
1791 fn nothing_is_true(self) {}
1795 let x = RefCell::new(TheDarkKnight);
1796 let x = x.into_inner(); // we get back ownership
1798 x.nothing_is_true(); // ok!
1805 use std::cell::RefCell;
1807 #[derive(Clone, Copy)] // we implement the Copy trait
1808 struct TheDarkKnight;
1810 impl TheDarkKnight {
1811 fn nothing_is_true(self) {}
1815 let x = RefCell::new(TheDarkKnight);
1817 x.borrow().nothing_is_true(); // ok!
1821 Moving a member out of a mutably borrowed struct will also cause E0507 error:
1823 ```compile_fail,E0507
1824 struct TheDarkKnight;
1826 impl TheDarkKnight {
1827 fn nothing_is_true(self) {}
1831 knight: TheDarkKnight
1835 let mut cave = Batcave {
1836 knight: TheDarkKnight
1838 let borrowed = &mut cave;
1840 borrowed.knight.nothing_is_true(); // E0507
1844 It is fine only if you put something back. `mem::replace` can be used for that:
1847 # struct TheDarkKnight;
1848 # impl TheDarkKnight { fn nothing_is_true(self) {} }
1849 # struct Batcave { knight: TheDarkKnight }
1852 let mut cave = Batcave {
1853 knight: TheDarkKnight
1855 let borrowed = &mut cave;
1857 mem::replace(&mut borrowed.knight, TheDarkKnight).nothing_is_true(); // ok!
1860 You can find more information about borrowing in the rust-book:
1861 http://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html
1865 A value was moved out of a non-copy fixed-size array.
1867 Erroneous code example:
1869 ```compile_fail,E0508
1873 let array = [NonCopy; 1];
1874 let _value = array[0]; // error: cannot move out of type `[NonCopy; 1]`,
1875 // a non-copy fixed-size array
1879 The first element was moved out of the array, but this is not
1880 possible because `NonCopy` does not implement the `Copy` trait.
1882 Consider borrowing the element instead of moving it:
1888 let array = [NonCopy; 1];
1889 let _value = &array[0]; // Borrowing is allowed, unlike moving.
1893 Alternatively, if your type implements `Clone` and you need to own the value,
1894 consider borrowing and then cloning:
1901 let array = [NonCopy; 1];
1902 // Now you can clone the array element.
1903 let _value = array[0].clone();
1909 This error occurs when an attempt is made to move out of a value whose type
1910 implements the `Drop` trait.
1912 Erroneous code example:
1914 ```compile_fail,E0509
1923 impl Drop for DropStruct {
1924 fn drop(&mut self) {
1925 // Destruct DropStruct, possibly using FancyNum
1930 let drop_struct = DropStruct{fancy: FancyNum{num: 5}};
1931 let fancy_field = drop_struct.fancy; // Error E0509
1932 println!("Fancy: {}", fancy_field.num);
1933 // implicit call to `drop_struct.drop()` as drop_struct goes out of scope
1937 Here, we tried to move a field out of a struct of type `DropStruct` which
1938 implements the `Drop` trait. However, a struct cannot be dropped if one or
1939 more of its fields have been moved.
1941 Structs implementing the `Drop` trait have an implicit destructor that gets
1942 called when they go out of scope. This destructor may use the fields of the
1943 struct, so moving out of the struct could make it impossible to run the
1944 destructor. Therefore, we must think of all values whose type implements the
1945 `Drop` trait as single units whose fields cannot be moved.
1947 This error can be fixed by creating a reference to the fields of a struct,
1948 enum, or tuple using the `ref` keyword:
1959 impl Drop for DropStruct {
1960 fn drop(&mut self) {
1961 // Destruct DropStruct, possibly using FancyNum
1966 let drop_struct = DropStruct{fancy: FancyNum{num: 5}};
1967 let ref fancy_field = drop_struct.fancy; // No more errors!
1968 println!("Fancy: {}", fancy_field.num);
1969 // implicit call to `drop_struct.drop()` as drop_struct goes out of scope
1973 Note that this technique can also be used in the arms of a match expression:
1984 impl Drop for DropEnum {
1985 fn drop(&mut self) {
1986 // Destruct DropEnum, possibly using FancyNum
1991 // Creates and enum of type `DropEnum`, which implements `Drop`
1992 let drop_enum = DropEnum::Fancy(FancyNum{num: 10});
1994 // Creates a reference to the inside of `DropEnum::Fancy`
1995 DropEnum::Fancy(ref fancy_field) => // No error!
1996 println!("It was fancy-- {}!", fancy_field.num),
1998 // implicit call to `drop_enum.drop()` as drop_enum goes out of scope
2004 Cannot mutate place in this match guard.
2006 When matching on a variable it cannot be mutated in the match guards, as this
2007 could cause the match to be non-exhaustive:
2009 ```compile_fail,E0510
2010 let mut x = Some(0);
2013 Some(_) if { x = None; false } => (),
2014 Some(v) => (), // No longer matches
2018 Here executing `x = None` would modify the value being matched and require us
2019 to go "back in time" to the `None` arm.
2023 Cannot return value that references local variable
2025 Local variables, function parameters and temporaries are all dropped before the
2026 end of the function body. So a reference to them cannot be returned.
2028 Erroneous code example:
2030 ```compile_fail,E0515
2031 fn get_dangling_reference() -> &'static i32 {
2037 ```compile_fail,E0515
2038 use std::slice::Iter;
2039 fn get_dangling_iterator<'a>() -> Iter<'a, i32> {
2040 let v = vec![1, 2, 3];
2045 Consider returning an owned value instead:
2048 use std::vec::IntoIter;
2050 fn get_integer() -> i32 {
2055 fn get_owned_iterator() -> IntoIter<i32> {
2056 let v = vec![1, 2, 3];
2063 A variable which requires unique access is being used in more than one closure
2066 Erroneous code example:
2068 ```compile_fail,E0524
2069 fn set(x: &mut isize) {
2073 fn dragoooon(x: &mut isize) {
2074 let mut c1 = || set(x);
2075 let mut c2 = || set(x); // error!
2082 To solve this issue, multiple solutions are available. First, is it required
2083 for this variable to be used in more than one closure at a time? If it is the
2084 case, use reference counted types such as `Rc` (or `Arc` if it runs
2089 use std::cell::RefCell;
2091 fn set(x: &mut isize) {
2095 fn dragoooon(x: &mut isize) {
2096 let x = Rc::new(RefCell::new(x));
2097 let y = Rc::clone(&x);
2098 let mut c1 = || { let mut x2 = x.borrow_mut(); set(&mut x2); };
2099 let mut c2 = || { let mut x2 = y.borrow_mut(); set(&mut x2); }; // ok!
2106 If not, just run closures one at a time:
2109 fn set(x: &mut isize) {
2113 fn dragoooon(x: &mut isize) {
2114 { // This block isn't necessary since non-lexical lifetimes, it's just to
2115 // make it more clear.
2116 let mut c1 = || set(&mut *x);
2118 } // `c1` has been dropped here so we're free to use `x` again!
2119 let mut c2 = || set(&mut *x);
2126 When matching against an exclusive range, the compiler verifies that the range
2127 is non-empty. Exclusive range patterns include the start point but not the end
2128 point, so this is equivalent to requiring the start of the range to be less
2129 than the end of the range.
2131 Erroneous code example:
2133 ```compile_fail,E0579
2134 #![feature(exclusive_range_pattern)]
2138 // This range is ok, albeit pointless.
2140 // This range is empty, and the compiler can tell.
2141 5 .. 5 => {} // error!
2148 #### Note: this error code is no longer emitted by the compiler.
2150 Closures cannot mutate immutable captured variables.
2152 Erroneous code example:
2154 ```compile_fail,E0594
2155 let x = 3; // error: closure cannot assign to immutable local variable `x`
2156 let mut c = || { x += 1 };
2159 Make the variable binding mutable:
2162 let mut x = 3; // ok!
2163 let mut c = || { x += 1 };
2168 This error occurs because you tried to mutably borrow a non-mutable variable.
2170 Erroneous code example:
2172 ```compile_fail,E0596
2174 let y = &mut x; // error: cannot borrow mutably
2177 In here, `x` isn't mutable, so when we try to mutably borrow it in `y`, it
2178 fails. To fix this error, you need to make `x` mutable:
2182 let y = &mut x; // ok!
2187 This error occurs because a value was dropped while it was still borrowed
2189 Erroneous code example:
2191 ```compile_fail,E0597
2196 let mut x = Foo { x: None };
2199 x.x = Some(&y); // error: `y` does not live long enough
2201 println!("{:?}", x.x);
2204 In here, `y` is dropped at the end of the inner scope, but it is borrowed by
2205 `x` until the `println`. To fix the previous example, just remove the scope
2206 so that `y` isn't dropped until after the println
2213 let mut x = Foo { x: None };
2218 println!("{:?}", x.x);
2223 This error occurs because a borrow in a generator persists across a
2226 Erroneous code example:
2228 ```compile_fail,E0626
2229 # #![feature(generators, generator_trait, pin)]
2230 # use std::ops::Generator;
2231 # use std::pin::Pin;
2233 let a = &String::new(); // <-- This borrow...
2234 yield (); // ...is still in scope here, when the yield occurs.
2237 Pin::new(&mut b).resume();
2240 At present, it is not permitted to have a yield that occurs while a
2241 borrow is still in scope. To resolve this error, the borrow must
2242 either be "contained" to a smaller scope that does not overlap the
2243 yield or else eliminated in another way. So, for example, we might
2244 resolve the previous example by removing the borrow and just storing
2245 the integer by value:
2248 # #![feature(generators, generator_trait, pin)]
2249 # use std::ops::Generator;
2250 # use std::pin::Pin;
2256 Pin::new(&mut b).resume();
2259 This is a very simple case, of course. In more complex cases, we may
2260 wish to have more than one reference to the value that was borrowed --
2261 in those cases, something like the `Rc` or `Arc` types may be useful.
2263 This error also frequently arises with iteration:
2265 ```compile_fail,E0626
2266 # #![feature(generators, generator_trait, pin)]
2267 # use std::ops::Generator;
2268 # use std::pin::Pin;
2270 let v = vec![1,2,3];
2271 for &x in &v { // <-- borrow of `v` is still in scope...
2272 yield x; // ...when this yield occurs.
2275 Pin::new(&mut b).resume();
2278 Such cases can sometimes be resolved by iterating "by value" (or using
2279 `into_iter()`) to avoid borrowing:
2282 # #![feature(generators, generator_trait, pin)]
2283 # use std::ops::Generator;
2284 # use std::pin::Pin;
2286 let v = vec![1,2,3];
2287 for x in v { // <-- Take ownership of the values instead!
2288 yield x; // <-- Now yield is OK.
2291 Pin::new(&mut b).resume();
2294 If taking ownership is not an option, using indices can work too:
2297 # #![feature(generators, generator_trait, pin)]
2298 # use std::ops::Generator;
2299 # use std::pin::Pin;
2301 let v = vec![1,2,3];
2302 let len = v.len(); // (*)
2304 let x = v[i]; // (*)
2305 yield x; // <-- Now yield is OK.
2308 Pin::new(&mut b).resume();
2310 // (*) -- Unfortunately, these temporaries are currently required.
2311 // See <https://github.com/rust-lang/rust/issues/43122>.
2316 This error occurs because a borrow of a thread-local variable was made inside a
2317 function which outlived the lifetime of the function.
2319 Erroneous code example:
2321 ```compile_fail,E0712
2322 #![feature(thread_local)]
2328 let a = &FOO; // error: thread-local variable borrowed past end of function
2330 std::thread::spawn(move || {
2338 This error occurs when an attempt is made to borrow state past the end of the
2339 lifetime of a type that implements the `Drop` trait.
2341 Erroneous code example:
2343 ```compile_fail,E0713
2346 pub struct S<'a> { data: &'a mut String }
2348 impl<'a> Drop for S<'a> {
2349 fn drop(&mut self) { self.data.push_str("being dropped"); }
2352 fn demo<'a>(s: S<'a>) -> &'a mut String { let p = &mut *s.data; p }
2355 Here, `demo` tries to borrow the string data held within its
2356 argument `s` and then return that borrow. However, `S` is
2357 declared as implementing `Drop`.
2359 Structs implementing the `Drop` trait have an implicit destructor that
2360 gets called when they go out of scope. This destructor gets exclusive
2361 access to the fields of the struct when it runs.
2363 This means that when `s` reaches the end of `demo`, its destructor
2364 gets exclusive access to its `&mut`-borrowed string data. allowing
2365 another borrow of that string data (`p`), to exist across the drop of
2366 `s` would be a violation of the principle that `&mut`-borrows have
2367 exclusive, unaliased access to their referenced data.
2369 This error can be fixed by changing `demo` so that the destructor does
2370 not run while the string-data is borrowed; for example by taking `S`
2374 pub struct S<'a> { data: &'a mut String }
2376 impl<'a> Drop for S<'a> {
2377 fn drop(&mut self) { self.data.push_str("being dropped"); }
2380 fn demo<'a>(s: &'a mut S<'a>) -> &'a mut String { let p = &mut *(*s).data; p }
2383 Note that this approach needs a reference to S with lifetime `'a`.
2384 Nothing shorter than `'a` will suffice: a shorter lifetime would imply
2385 that after `demo` finishes executing, something else (such as the
2386 destructor!) could access `s.data` after the end of that shorter
2387 lifetime, which would again violate the `&mut`-borrow's exclusive
2392 This error indicates that a temporary value is being dropped
2393 while a borrow is still in active use.
2395 Erroneous code example:
2397 ```compile_fail,E0716
2398 fn foo() -> i32 { 22 }
2399 fn bar(x: &i32) -> &i32 { x }
2400 let p = bar(&foo());
2401 // ------ creates a temporary
2405 Here, the expression `&foo()` is borrowing the expression
2406 `foo()`. As `foo()` is a call to a function, and not the name of
2407 a variable, this creates a **temporary** -- that temporary stores
2408 the return value from `foo()` so that it can be borrowed.
2409 You could imagine that `let p = bar(&foo());` is equivalent
2412 ```compile_fail,E0597
2413 # fn foo() -> i32 { 22 }
2414 # fn bar(x: &i32) -> &i32 { x }
2416 let tmp = foo(); // the temporary
2418 }; // <-- tmp is freed as we exit this block
2422 Whenever a temporary is created, it is automatically dropped (freed)
2423 according to fixed rules. Ordinarily, the temporary is dropped
2424 at the end of the enclosing statement -- in this case, after the `let`.
2425 This is illustrated in the example above by showing that `tmp` would
2426 be freed as we exit the block.
2428 To fix this problem, you need to create a local variable
2429 to store the value in rather than relying on a temporary.
2430 For example, you might change the original program to
2434 fn foo() -> i32 { 22 }
2435 fn bar(x: &i32) -> &i32 { x }
2436 let value = foo(); // dropped at the end of the enclosing block
2437 let p = bar(&value);
2441 By introducing the explicit `let value`, we allocate storage
2442 that will last until the end of the enclosing block (when `value`
2443 goes out of scope). When we borrow `&value`, we are borrowing a
2444 local variable that already exists, and hence no temporary is created.
2446 Temporaries are not always dropped at the end of the enclosing
2447 statement. In simple cases where the `&` expression is immediately
2448 stored into a variable, the compiler will automatically extend
2449 the lifetime of the temporary until the end of the enclosing
2450 block. Therefore, an alternative way to fix the original
2451 program is to write `let tmp = &foo()` and not `let tmp = foo()`:
2454 fn foo() -> i32 { 22 }
2455 fn bar(x: &i32) -> &i32 { x }
2461 Here, we are still borrowing `foo()`, but as the borrow is assigned
2462 directly into a variable, the temporary will not be dropped until
2463 the end of the enclosing block. Similar rules apply when temporaries
2464 are stored into aggregate structures like a tuple or struct:
2467 // Here, two temporaries are created, but
2468 // as they are stored directly into `value`,
2469 // they are not dropped until the end of the
2471 fn foo() -> i32 { 22 }
2472 let value = (&foo(), &foo());
2477 An feature unstable in `const` contexts was used.
2479 Erroneous code example:
2481 ```compile_fail,E0723
2486 const fn foo() -> impl T { // error: `impl Trait` in const fn is unstable
2491 To enable this feature on a nightly version of rustc, add the `const_fn`
2495 #![feature(const_fn)]
2501 const fn foo() -> impl T {
2508 Support for Non-Lexical Lifetimes (NLL) has been included in the Rust compiler
2509 since 1.31, and has been enabled on the 2015 edition since 1.36. The new borrow
2510 checker for NLL uncovered some bugs in the old borrow checker, which in some
2511 cases allowed unsound code to compile, resulting in memory safety issues.
2515 Change your code so the warning does no longer trigger. For backwards
2516 compatibility, this unsound code may still compile (with a warning) right now.
2517 However, at some point in the future, the compiler will no longer accept this
2518 code and will throw a hard error.
2520 ### Shouldn't you fix the old borrow checker?
2522 The old borrow checker has known soundness issues that are basically impossible
2523 to fix. The new NLL-based borrow checker is the fix.
2525 ### Can I turn these warnings into errors by denying a lint?
2529 ### When are these warnings going to turn into errors?
2531 No formal timeline for turning the warnings into errors has been set. See
2532 [GitHub issue 58781](https://github.com/rust-lang/rust/issues/58781) for more
2535 ### Why do I get this message with code that doesn't involve borrowing?
2537 There are some known bugs that trigger this message.
2542 // E0008, // cannot bind by-move into a pattern guard
2543 // E0298, // cannot compare constants
2544 // E0299, // mismatched types between arms
2545 // E0471, // constant evaluation error (in pattern)
2546 // E0385, // {} in an aliasable location
2547 E0521, // borrowed data escapes outside of closure
2548 E0526, // shuffle indices are not constant
2549 E0594, // cannot assign to {}
2550 // E0598, // lifetime of {} is too short to guarantee its contents can be...
2551 E0625, // thread-local statics cannot be accessed at compile-time