1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![allow(non_snake_case)]
13 register_long_diagnostics
! {
16 This error occurs when an attempt is made to use data captured by a closure,
17 when that data may no longer exist. It's most commonly seen when attempting to
21 fn foo() -> Box<Fn(u32) -> u32> {
27 Notice that `x` is stack-allocated by `foo()`. By default, Rust captures
28 closed-over data by reference. This means that once `foo()` returns, `x` no
29 longer exists. An attempt to access `x` within the closure would thus be
32 Another situation where this might be encountered is when spawning threads:
39 let thr = std::thread::spawn(|| {
45 Since our new thread runs in parallel, the stack frame containing `x` and `y`
46 may well have disappeared by the time we try to use them. Even if we call
47 `thr.join()` within foo (which blocks until `thr` has completed, ensuring the
48 stack frame won't disappear), we will not succeed: the compiler cannot prove
49 that this behaviour is safe, and so won't let us do it.
51 The solution to this problem is usually to switch to using a `move` closure.
52 This approach moves (or copies, where possible) data into the closure, rather
53 than taking references to it. For example:
56 fn foo() -> Box<Fn(u32) -> u32> {
58 Box::new(move |y| x + y)
62 Now that the closure has its own copy of the data, there's no need to worry
67 It is not allowed to use or capture an uninitialized variable. For example:
72 let y = x; // error, use of possibly uninitialized variable
76 To fix this, ensure that any declared variables are initialized before being
88 This error occurs when an attempt is made to use a variable after its contents
89 have been moved elsewhere. For example:
92 struct MyStruct { s: u32 }
95 let mut x = MyStruct{ s: 5u32 };
102 Since `MyStruct` is a type that is not marked `Copy`, the data gets moved out
103 of `x` when we set `y`. This is fundamental to Rust's ownership system: outside
104 of workarounds like `Rc`, a value cannot be owned by more than one variable.
106 If we own the type, the easiest way to address this problem is to implement
107 `Copy` and `Clone` on it, as shown below. This allows `y` to copy the
108 information in `x`, while leaving the original version owned by `x`. Subsequent
109 changes to `x` will not be reflected when accessing `y`.
112 #[derive(Copy, Clone)]
113 struct MyStruct { s: u32 }
116 let mut x = MyStruct{ s: 5u32 };
123 Alternatively, if we don't control the struct's definition, or mutable shared
124 ownership is truly required, we can use `Rc` and `RefCell`:
127 use std::cell::RefCell;
130 struct MyStruct { s: u32 }
133 let mut x = Rc::new(RefCell::new(MyStruct{ s: 5u32 }));
135 x.borrow_mut().s = 6;
136 println!("{}", x.borrow().s);
140 With this approach, x and y share ownership of the data via the `Rc` (reference
141 count type). `RefCell` essentially performs runtime borrow checking: ensuring
142 that at most one writer or multiple readers can access the data at any one time.
144 If you wish to learn more about ownership in Rust, start with the chapter in the
147 https://doc.rust-lang.org/book/ownership.html
151 This error occurs when an attempt is made to partially reinitialize a
152 structure that is currently uninitialized.
154 For example, this can happen when a drop has taken place:
161 let mut x = Foo { a: 1 };
162 drop(x); // `x` is now uninitialized
163 x.a = 2; // error, partial reinitialization of uninitialized structure `t`
166 This error can be fixed by fully reinitializing the structure in question:
173 let mut x = Foo { a: 1 };
180 This error occurs when an attempt is made to reassign an immutable variable.
183 ```compile_fail,E0384
186 x = 5; // error, reassignment of immutable variable
190 By default, variables in Rust are immutable. To fix this error, add the keyword
191 `mut` after the keyword `let` when declaring the variable. For example:
202 This error occurs when an attempt is made to mutate the target of a mutable
203 reference stored inside an immutable container.
205 For example, this can happen when storing a `&mut` inside an immutable `Box`:
207 ```compile_fail,E0386
209 let y: Box<_> = Box::new(&mut x);
210 **y = 2; // error, cannot assign to data in an immutable container
213 This error can be fixed by making the container mutable:
217 let mut y: Box<_> = Box::new(&mut x);
221 It can also be fixed by using a type with interior mutability, such as `Cell`
228 let y: Box<Cell<_>> = Box::new(Cell::new(x));
234 This error occurs when an attempt is made to mutate or mutably reference data
235 that a closure has captured immutably. Examples of this error are shown below:
237 ```compile_fail,E0387
238 // Accepts a function or a closure that captures its environment immutably.
239 // Closures passed to foo will not be able to mutate their closed-over state.
240 fn foo<F: Fn()>(f: F) { }
242 // Attempts to mutate closed-over data. Error message reads:
243 // `cannot assign to data in a captured outer variable...`
249 // Attempts to take a mutable reference to closed-over data. Error message
250 // reads: `cannot borrow data mutably in a captured outer variable...`
253 foo(|| { let y = &mut x; });
257 The problem here is that foo is defined as accepting a parameter of type `Fn`.
258 Closures passed into foo will thus be inferred to be of type `Fn`, meaning that
259 they capture their context immutably.
261 If the definition of `foo` is under your control, the simplest solution is to
262 capture the data mutably. This can be done by defining `foo` to take FnMut
266 fn foo<F: FnMut()>(f: F) { }
269 Alternatively, we can consider using the `Cell` and `RefCell` types to achieve
270 interior mutability through a shared reference. Our example's `mutable`
271 function could be redefined as below:
276 fn foo<F: Fn()>(f: F) { }
279 let x = Cell::new(0u32);
284 You can read more about cell types in the API documentation:
286 https://doc.rust-lang.org/std/cell/
290 A mutable borrow was attempted in a static location.
292 Erroneous code example:
294 ```compile_fail,E0388
297 static STATIC_REF: &'static mut i32 = &mut X;
298 // error: cannot borrow data mutably in a static location
300 const CONST_REF: &'static mut i32 = &mut X;
301 // error: cannot borrow data mutably in a static location
304 To fix this error, you have to use constant borrow:
309 static STATIC_REF: &'static i32 = &X;
314 An attempt was made to mutate data using a non-mutable reference. This
315 commonly occurs when attempting to assign to a non-mutable reference of a
316 mutable reference (`&(&mut T)`).
318 Example of erroneous code:
320 ```compile_fail,E0389
326 let mut fancy = FancyNum{ num: 5 };
327 let fancy_ref = &(&mut fancy);
328 fancy_ref.num = 6; // error: cannot assign to data in a `&` reference
329 println!("{}", fancy_ref.num);
333 Here, `&mut fancy` is mutable, but `&(&mut fancy)` is not. Creating an
334 immutable reference to a value borrows it immutably. There can be multiple
335 references of type `&(&mut T)` that point to the same value, so they must be
336 immutable to prevent multiple mutable references to the same value.
338 To fix this, either remove the outer reference:
346 let mut fancy = FancyNum{ num: 5 };
348 let fancy_ref = &mut fancy;
349 // `fancy_ref` is now &mut FancyNum, rather than &(&mut FancyNum)
351 fancy_ref.num = 6; // No error!
353 println!("{}", fancy_ref.num);
357 Or make the outer reference mutable:
365 let mut fancy = FancyNum{ num: 5 };
367 let fancy_ref = &mut (&mut fancy);
368 // `fancy_ref` is now &mut(&mut FancyNum), rather than &(&mut FancyNum)
370 fancy_ref.num = 6; // No error!
372 println!("{}", fancy_ref.num);
378 A variable was borrowed as mutable more than once. Erroneous code example:
380 ```compile_fail,E0499
384 // error: cannot borrow `i` as mutable more than once at a time
387 Please note that in rust, you can either have many immutable references, or one
388 mutable reference. Take a look at
389 https://doc.rust-lang.org/stable/book/references-and-borrowing.html for more
390 information. Example:
395 let mut x = &mut i; // ok!
400 let b = &i; // still ok!
401 let c = &i; // still ok!
406 A borrowed variable was used in another closure. Example of erroneous code:
409 fn you_know_nothing(jon_snow: &mut i32) {
410 let nights_watch = || {
414 *jon_snow = 3; // error: closure requires unique access to `jon_snow`
415 // but it is already borrowed
420 In here, `jon_snow` is already borrowed by the `nights_watch` closure, so it
421 cannot be borrowed by the `starks` closure at the same time. To fix this issue,
422 you can put the closure in its own scope:
425 fn you_know_nothing(jon_snow: &mut i32) {
427 let nights_watch = || {
430 } // At this point, `jon_snow` is free.
437 Or, if the type implements the `Clone` trait, you can clone it between
441 fn you_know_nothing(jon_snow: &mut i32) {
442 let mut jon_copy = jon_snow.clone();
443 let nights_watch = || {
454 This error indicates that a mutable variable is being used while it is still
455 captured by a closure. Because the closure has borrowed the variable, it is not
456 available for use until the closure goes out of scope.
458 Note that a capture will either move or borrow a variable, but in this
459 situation, the closure is borrowing the variable. Take a look at
460 http://rustbyexample.com/fn/closures/capture.html for more information about
463 Example of erroneous code:
465 ```compile_fail,E0501
466 fn inside_closure(x: &mut i32) {
467 // Actions which require unique access
470 fn outside_closure(x: &mut i32) {
471 // Actions which require unique access
474 fn foo(a: &mut i32) {
478 outside_closure(a); // error: cannot borrow `*a` as mutable because previous
479 // closure requires unique access.
483 To fix this error, you can place the closure in its own scope:
486 fn inside_closure(x: &mut i32) {}
487 fn outside_closure(x: &mut i32) {}
489 fn foo(a: &mut i32) {
494 } // borrow on `a` ends.
495 outside_closure(a); // ok!
499 Or you can pass the variable as a parameter to the closure:
502 fn inside_closure(x: &mut i32) {}
503 fn outside_closure(x: &mut i32) {}
505 fn foo(a: &mut i32) {
506 let bar = |s: &mut i32| {
514 It may be possible to define the closure later:
517 fn inside_closure(x: &mut i32) {}
518 fn outside_closure(x: &mut i32) {}
520 fn foo(a: &mut i32) {
530 This error indicates that you are trying to borrow a variable as mutable when it
531 has already been borrowed as immutable.
533 Example of erroneous code:
535 ```compile_fail,E0502
536 fn bar(x: &mut i32) {}
537 fn foo(a: &mut i32) {
538 let ref y = a; // a is borrowed as immutable.
539 bar(a); // error: cannot borrow `*a` as mutable because `a` is also borrowed
544 To fix this error, ensure that you don't have any other references to the
545 variable before trying to access it mutably:
548 fn bar(x: &mut i32) {}
549 fn foo(a: &mut i32) {
551 let ref y = a; // ok!
555 For more information on the rust ownership system, take a look at
556 https://doc.rust-lang.org/stable/book/references-and-borrowing.html.
560 A value was used after it was mutably borrowed.
562 Example of erroneous code:
564 ```compile_fail,E0503
567 // Create a mutable borrow of `value`. This borrow
568 // lives until the end of this function.
569 let _borrow = &mut value;
570 let _sum = value + 1; // error: cannot use `value` because
571 // it was mutably borrowed
575 In this example, `value` is mutably borrowed by `borrow` and cannot be
576 used to calculate `sum`. This is not possible because this would violate
577 Rust's mutability rules.
579 You can fix this error by limiting the scope of the borrow:
584 // By creating a new block, you can limit the scope
587 let _borrow = &mut value; // Use `_borrow` inside this block.
589 // The block has ended and with it the borrow.
590 // You can now use `value` again.
591 let _sum = value + 1;
595 Or by cloning `value` before borrowing it:
600 // We clone `value`, creating a copy.
601 let value_cloned = value.clone();
602 // The mutable borrow is a reference to `value` and
603 // not to `value_cloned`...
604 let _borrow = &mut value;
605 // ... which means we can still use `value_cloned`,
606 let _sum = value_cloned + 1;
607 // even though the borrow only ends here.
611 You can find more information about borrowing in the rust-book:
612 http://doc.rust-lang.org/stable/book/references-and-borrowing.html
616 This error occurs when an attempt is made to move a borrowed variable into a
619 Example of erroneous code:
621 ```compile_fail,E0504
627 let fancy_num = FancyNum { num: 5 };
628 let fancy_ref = &fancy_num;
631 println!("child function: {}", fancy_num.num);
632 // error: cannot move `fancy_num` into closure because it is borrowed
636 println!("main function: {}", fancy_ref.num);
640 Here, `fancy_num` is borrowed by `fancy_ref` and so cannot be moved into
641 the closure `x`. There is no way to move a value into a closure while it is
642 borrowed, as that would invalidate the borrow.
644 If the closure can't outlive the value being moved, try using a reference
653 let fancy_num = FancyNum { num: 5 };
654 let fancy_ref = &fancy_num;
657 // fancy_ref is usable here because it doesn't move `fancy_num`
658 println!("child function: {}", fancy_ref.num);
663 println!("main function: {}", fancy_num.num);
667 If the value has to be borrowed and then moved, try limiting the lifetime of
668 the borrow using a scoped block:
676 let fancy_num = FancyNum { num: 5 };
679 let fancy_ref = &fancy_num;
680 println!("main function: {}", fancy_ref.num);
681 // `fancy_ref` goes out of scope here
685 // `fancy_num` can be moved now (no more references exist)
686 println!("child function: {}", fancy_num.num);
693 If the lifetime of a reference isn't enough, such as in the case of threading,
694 consider using an `Arc` to create a reference-counted value:
705 let fancy_ref1 = Arc::new(FancyNum { num: 5 });
706 let fancy_ref2 = fancy_ref1.clone();
708 let x = thread::spawn(move || {
709 // `fancy_ref1` can be moved and has a `'static` lifetime
710 println!("child thread: {}", fancy_ref1.num);
713 x.join().expect("child thread should finish");
714 println!("main thread: {}", fancy_ref2.num);
720 A value was moved out while it was still borrowed.
722 Erroneous code example:
724 ```compile_fail,E0505
727 fn eat(val: Value) {}
732 let _ref_to_val: &Value = &x;
738 Here, the function `eat` takes the ownership of `x`. However,
739 `x` cannot be moved because it was borrowed to `_ref_to_val`.
740 To fix that you can do few different things:
742 * Try to avoid moving the variable.
743 * Release borrow before move.
744 * Implement the `Copy` trait on the type.
751 fn eat(val: &Value) {}
756 let _ref_to_val: &Value = &x;
757 eat(&x); // pass by reference, if it's possible
767 fn eat(val: Value) {}
772 let _ref_to_val: &Value = &x;
774 eat(x); // release borrow and then move it.
781 #[derive(Clone, Copy)] // implement Copy trait
784 fn eat(val: Value) {}
789 let _ref_to_val: &Value = &x;
790 eat(x); // it will be copied here.
795 You can find more information about borrowing in the rust-book:
796 http://doc.rust-lang.org/stable/book/references-and-borrowing.html
800 This error occurs when an attempt is made to assign to a borrowed value.
802 Example of erroneous code:
804 ```compile_fail,E0506
810 let mut fancy_num = FancyNum { num: 5 };
811 let fancy_ref = &fancy_num;
812 fancy_num = FancyNum { num: 6 };
813 // error: cannot assign to `fancy_num` because it is borrowed
815 println!("Num: {}, Ref: {}", fancy_num.num, fancy_ref.num);
819 Because `fancy_ref` still holds a reference to `fancy_num`, `fancy_num` can't
820 be assigned to a new value as it would invalidate the reference.
822 Alternatively, we can move out of `fancy_num` into a second `fancy_num`:
830 let mut fancy_num = FancyNum { num: 5 };
831 let moved_num = fancy_num;
832 fancy_num = FancyNum { num: 6 };
834 println!("Num: {}, Moved num: {}", fancy_num.num, moved_num.num);
838 If the value has to be borrowed, try limiting the lifetime of the borrow using
847 let mut fancy_num = FancyNum { num: 5 };
850 let fancy_ref = &fancy_num;
851 println!("Ref: {}", fancy_ref.num);
854 // Works because `fancy_ref` is no longer in scope
855 fancy_num = FancyNum { num: 6 };
856 println!("Num: {}", fancy_num.num);
860 Or by moving the reference into a function:
868 let mut fancy_num = FancyNum { num: 5 };
870 print_fancy_ref(&fancy_num);
872 // Works because function borrow has ended
873 fancy_num = FancyNum { num: 6 };
874 println!("Num: {}", fancy_num.num);
877 fn print_fancy_ref(fancy_ref: &FancyNum){
878 println!("Ref: {}", fancy_ref.num);
884 You tried to move out of a value which was borrowed. Erroneous code example:
886 ```compile_fail,E0507
887 use std::cell::RefCell;
889 struct TheDarkKnight;
892 fn nothing_is_true(self) {}
896 let x = RefCell::new(TheDarkKnight);
898 x.borrow().nothing_is_true(); // error: cannot move out of borrowed content
902 Here, the `nothing_is_true` method takes the ownership of `self`. However,
903 `self` cannot be moved because `.borrow()` only provides an `&TheDarkKnight`,
904 which is a borrow of the content owned by the `RefCell`. To fix this error,
905 you have three choices:
907 * Try to avoid moving the variable.
908 * Somehow reclaim the ownership.
909 * Implement the `Copy` trait on the type.
914 use std::cell::RefCell;
916 struct TheDarkKnight;
919 fn nothing_is_true(&self) {} // First case, we don't take ownership
923 let x = RefCell::new(TheDarkKnight);
925 x.borrow().nothing_is_true(); // ok!
932 use std::cell::RefCell;
934 struct TheDarkKnight;
937 fn nothing_is_true(self) {}
941 let x = RefCell::new(TheDarkKnight);
942 let x = x.into_inner(); // we get back ownership
944 x.nothing_is_true(); // ok!
951 use std::cell::RefCell;
953 #[derive(Clone, Copy)] // we implement the Copy trait
954 struct TheDarkKnight;
957 fn nothing_is_true(self) {}
961 let x = RefCell::new(TheDarkKnight);
963 x.borrow().nothing_is_true(); // ok!
967 Moving out of a member of a mutably borrowed struct is fine if you put something
968 back. `mem::replace` can be used for that:
971 struct TheDarkKnight;
974 fn nothing_is_true(self) {}
978 knight: TheDarkKnight
984 let mut cave = Batcave {
985 knight: TheDarkKnight
987 let borrowed = &mut cave;
989 borrowed.knight.nothing_is_true(); // E0507
990 mem::replace(&mut borrowed.knight, TheDarkKnight).nothing_is_true(); // ok!
994 You can find more information about borrowing in the rust-book:
995 http://doc.rust-lang.org/stable/book/references-and-borrowing.html
999 A value was moved out of a non-copy fixed-size array.
1001 Example of erroneous code:
1003 ```compile_fail,E0508
1007 let array = [NonCopy; 1];
1008 let _value = array[0]; // error: cannot move out of type `[NonCopy; 1]`,
1009 // a non-copy fixed-size array
1013 The first element was moved out of the array, but this is not
1014 possible because `NonCopy` does not implement the `Copy` trait.
1016 Consider borrowing the element instead of moving it:
1022 let array = [NonCopy; 1];
1023 let _value = &array[0]; // Borrowing is allowed, unlike moving.
1027 Alternatively, if your type implements `Clone` and you need to own the value,
1028 consider borrowing and then cloning:
1035 let array = [NonCopy; 1];
1036 // Now you can clone the array element.
1037 let _value = array[0].clone();
1043 This error occurs when an attempt is made to move out of a value whose type
1044 implements the `Drop` trait.
1046 Example of erroneous code:
1048 ```compile_fail,E0509
1057 impl Drop for DropStruct {
1058 fn drop(&mut self) {
1059 // Destruct DropStruct, possibly using FancyNum
1064 let drop_struct = DropStruct{fancy: FancyNum{num: 5}};
1065 let fancy_field = drop_struct.fancy; // Error E0509
1066 println!("Fancy: {}", fancy_field.num);
1067 // implicit call to `drop_struct.drop()` as drop_struct goes out of scope
1071 Here, we tried to move a field out of a struct of type `DropStruct` which
1072 implements the `Drop` trait. However, a struct cannot be dropped if one or
1073 more of its fields have been moved.
1075 Structs implementing the `Drop` trait have an implicit destructor that gets
1076 called when they go out of scope. This destructor may use the fields of the
1077 struct, so moving out of the struct could make it impossible to run the
1078 destructor. Therefore, we must think of all values whose type implements the
1079 `Drop` trait as single units whose fields cannot be moved.
1081 This error can be fixed by creating a reference to the fields of a struct,
1082 enum, or tuple using the `ref` keyword:
1093 impl Drop for DropStruct {
1094 fn drop(&mut self) {
1095 // Destruct DropStruct, possibly using FancyNum
1100 let drop_struct = DropStruct{fancy: FancyNum{num: 5}};
1101 let ref fancy_field = drop_struct.fancy; // No more errors!
1102 println!("Fancy: {}", fancy_field.num);
1103 // implicit call to `drop_struct.drop()` as drop_struct goes out of scope
1107 Note that this technique can also be used in the arms of a match expression:
1118 impl Drop for DropEnum {
1119 fn drop(&mut self) {
1120 // Destruct DropEnum, possibly using FancyNum
1125 // Creates and enum of type `DropEnum`, which implements `Drop`
1126 let drop_enum = DropEnum::Fancy(FancyNum{num: 10});
1128 // Creates a reference to the inside of `DropEnum::Fancy`
1129 DropEnum::Fancy(ref fancy_field) => // No error!
1130 println!("It was fancy-- {}!", fancy_field.num),
1132 // implicit call to `drop_enum.drop()` as drop_enum goes out of scope
1139 register_diagnostics
! {
1140 E0385
, // {} in an aliasable location
1141 E0524
, // two closures require unique access to `..` at the same time