1 // Copyright 2015 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 The value of statics and constants must be known at compile time, and they live
17 for the entire lifetime of a program. Creating a boxed value allocates memory on
18 the heap at runtime, and therefore cannot be done at compile time. Erroneous
22 #![feature(box_syntax)]
24 const CON : Box<i32> = box 0;
29 Static and const variables can refer to other const variables. But a const
30 variable cannot refer to a static variable. For example, `Y` cannot refer to
38 To fix this, the value can be extracted as a const and then used:
47 // FIXME(#24111) Change the language here when const fn stabilizes
49 The only functions that can be called in static or constant expressions are
50 `const` functions, and struct/enum constructors. `const` functions are only
51 available on a nightly compiler. Rust currently does not support more general
52 compile-time function execution.
55 const FOO: Option<u8> = Some(1); // enum constructor
57 const BAR: Bar = Bar {x: 1}; // struct constructor
60 See [RFC 911] for more details on the design of `const fn`s.
62 [RFC 911]: https://github.com/rust-lang/rfcs/blob/master/text/0911-const-fn.md
66 Blocks in constants may only contain items (such as constant, function
67 definition, etc...) and a tail expression. Erroneous code example:
70 const FOO: i32 = { let x = 0; x }; // 'x' isn't an item!
73 To avoid it, you have to replace the non-item object:
76 const FOO: i32 = { const X : i32 = 0; X };
81 References in statics and constants may only refer to immutable values.
82 Erroneous code example:
88 // these three are not allowed:
89 const CR: &'static mut i32 = &mut C;
90 static STATIC_REF: &'static mut i32 = &mut X;
91 static CONST_REF: &'static mut i32 = &mut C;
94 Statics are shared everywhere, and if they refer to mutable data one might
95 violate memory safety since holding multiple mutable references to shared data
98 If you really want global mutable state, try using `static mut` or a global
104 The value of static and constant integers must be known at compile time. You
105 can't cast a pointer to an integer because the address of a pointer can
108 For example, if you write:
110 ```compile_fail,E0018
111 static MY_STATIC: u32 = 42;
112 static MY_STATIC_ADDR: usize = &MY_STATIC as *const _ as usize;
113 static WHAT: usize = (MY_STATIC_ADDR^17) + MY_STATIC_ADDR;
116 Then `MY_STATIC_ADDR` would contain the address of `MY_STATIC`. However,
117 the address can change when the program is linked, as well as change
118 between different executions due to ASLR, and many linkers would
119 not be able to calculate the value of `WHAT`.
121 On the other hand, static and constant pointers can point either to
122 a known numeric address or to the address of a symbol.
125 static MY_STATIC: u32 = 42;
126 static MY_STATIC_ADDR: &'static u32 = &MY_STATIC;
127 const CONST_ADDR: *const u8 = 0x5f3759df as *const u8;
130 This does not pose a problem by itself because they can't be
135 A function call isn't allowed in the const's initialization expression
136 because the expression's value must be known at compile-time. Erroneous code
145 fn test(&self) -> i32 {
151 const FOO: Test = Test::V1;
153 const A: i32 = FOO.test(); // You can't call Test::func() here!
157 Remember: you can't use a function call inside a const's initialization
158 expression! However, you can totally use it anywhere else:
166 fn func(&self) -> i32 {
172 const FOO: Test = Test::V1;
174 FOO.func(); // here is good
175 let x = FOO.func(); // or even here!
181 Constant functions are not allowed to mutate anything. Thus, binding to an
182 argument with a mutable pattern is not allowed. For example,
185 const fn foo(mut x: u8) {
190 Is incorrect because the function body may not mutate `x`.
192 Remove any mutable bindings from the argument list to fix this error. In case
193 you need to mutate the argument, try lazily initializing a global variable
194 instead of using a `const fn`, or refactoring the code to a functional style to
195 avoid mutation if possible.
199 Unsafe code was used outside of an unsafe function or block.
201 Erroneous code example:
203 ```compile_fail,E0133
204 unsafe fn f() { return; } // This is the unsafe code
207 f(); // error: call to unsafe function requires unsafe function or block
211 Using unsafe functionality is potentially dangerous and disallowed by safety
214 * Dereferencing raw pointers
215 * Calling functions via FFI
216 * Calling functions marked unsafe
218 These safety checks can be relaxed for a section of the code by wrapping the
219 unsafe instructions with an `unsafe` block. For instance:
222 unsafe fn f() { return; }
225 unsafe { f(); } // ok!
229 See also https://doc.rust-lang.org/book/first-edition/unsafe.html
233 This error occurs when an attempt is made to use data captured by a closure,
234 when that data may no longer exist. It's most commonly seen when attempting to
237 ```compile_fail,E0373
238 fn foo() -> Box<Fn(u32) -> u32> {
244 Notice that `x` is stack-allocated by `foo()`. By default, Rust captures
245 closed-over data by reference. This means that once `foo()` returns, `x` no
246 longer exists. An attempt to access `x` within the closure would thus be
249 Another situation where this might be encountered is when spawning threads:
251 ```compile_fail,E0373
256 let thr = std::thread::spawn(|| {
262 Since our new thread runs in parallel, the stack frame containing `x` and `y`
263 may well have disappeared by the time we try to use them. Even if we call
264 `thr.join()` within foo (which blocks until `thr` has completed, ensuring the
265 stack frame won't disappear), we will not succeed: the compiler cannot prove
266 that this behaviour is safe, and so won't let us do it.
268 The solution to this problem is usually to switch to using a `move` closure.
269 This approach moves (or copies, where possible) data into the closure, rather
270 than taking references to it. For example:
273 fn foo() -> Box<Fn(u32) -> u32> {
275 Box::new(move |y| x + y)
279 Now that the closure has its own copy of the data, there's no need to worry
284 It is not allowed to use or capture an uninitialized variable. For example:
286 ```compile_fail,E0381
289 let y = x; // error, use of possibly uninitialized variable
293 To fix this, ensure that any declared variables are initialized before being
305 This error occurs when an attempt is made to use a variable after its contents
306 have been moved elsewhere. For example:
308 ```compile_fail,E0382
309 struct MyStruct { s: u32 }
312 let mut x = MyStruct{ s: 5u32 };
319 Since `MyStruct` is a type that is not marked `Copy`, the data gets moved out
320 of `x` when we set `y`. This is fundamental to Rust's ownership system: outside
321 of workarounds like `Rc`, a value cannot be owned by more than one variable.
323 If we own the type, the easiest way to address this problem is to implement
324 `Copy` and `Clone` on it, as shown below. This allows `y` to copy the
325 information in `x`, while leaving the original version owned by `x`. Subsequent
326 changes to `x` will not be reflected when accessing `y`.
329 #[derive(Copy, Clone)]
330 struct MyStruct { s: u32 }
333 let mut x = MyStruct{ s: 5u32 };
340 Alternatively, if we don't control the struct's definition, or mutable shared
341 ownership is truly required, we can use `Rc` and `RefCell`:
344 use std::cell::RefCell;
347 struct MyStruct { s: u32 }
350 let mut x = Rc::new(RefCell::new(MyStruct{ s: 5u32 }));
352 x.borrow_mut().s = 6;
353 println!("{}", x.borrow().s);
357 With this approach, x and y share ownership of the data via the `Rc` (reference
358 count type). `RefCell` essentially performs runtime borrow checking: ensuring
359 that at most one writer or multiple readers can access the data at any one time.
361 If you wish to learn more about ownership in Rust, start with the chapter in the
364 https://doc.rust-lang.org/book/first-edition/ownership.html
368 This error occurs when an attempt is made to partially reinitialize a
369 structure that is currently uninitialized.
371 For example, this can happen when a drop has taken place:
373 ```compile_fail,E0383
378 fn drop(&mut self) { /* ... */ }
381 let mut x = Foo { a: 1 };
382 drop(x); // `x` is now uninitialized
383 x.a = 2; // error, partial reinitialization of uninitialized structure `t`
386 This error can be fixed by fully reinitializing the structure in question:
393 fn drop(&mut self) { /* ... */ }
396 let mut x = Foo { a: 1 };
403 This error occurs when an attempt is made to reassign an immutable variable.
406 ```compile_fail,E0384
409 x = 5; // error, reassignment of immutable variable
413 By default, variables in Rust are immutable. To fix this error, add the keyword
414 `mut` after the keyword `let` when declaring the variable. For example:
425 This error occurs when an attempt is made to mutate the target of a mutable
426 reference stored inside an immutable container.
428 For example, this can happen when storing a `&mut` inside an immutable `Box`:
430 ```compile_fail,E0386
432 let y: Box<_> = Box::new(&mut x);
433 **y = 2; // error, cannot assign to data in an immutable container
436 This error can be fixed by making the container mutable:
440 let mut y: Box<_> = Box::new(&mut x);
444 It can also be fixed by using a type with interior mutability, such as `Cell`
451 let y: Box<Cell<_>> = Box::new(Cell::new(x));
457 This error occurs when an attempt is made to mutate or mutably reference data
458 that a closure has captured immutably. Examples of this error are shown below:
460 ```compile_fail,E0387
461 // Accepts a function or a closure that captures its environment immutably.
462 // Closures passed to foo will not be able to mutate their closed-over state.
463 fn foo<F: Fn()>(f: F) { }
465 // Attempts to mutate closed-over data. Error message reads:
466 // `cannot assign to data in a captured outer variable...`
472 // Attempts to take a mutable reference to closed-over data. Error message
473 // reads: `cannot borrow data mutably in a captured outer variable...`
476 foo(|| { let y = &mut x; });
480 The problem here is that foo is defined as accepting a parameter of type `Fn`.
481 Closures passed into foo will thus be inferred to be of type `Fn`, meaning that
482 they capture their context immutably.
484 If the definition of `foo` is under your control, the simplest solution is to
485 capture the data mutably. This can be done by defining `foo` to take FnMut
489 fn foo<F: FnMut()>(f: F) { }
492 Alternatively, we can consider using the `Cell` and `RefCell` types to achieve
493 interior mutability through a shared reference. Our example's `mutable`
494 function could be redefined as below:
499 fn foo<F: Fn()>(f: F) { }
502 let x = Cell::new(0u32);
507 You can read more about cell types in the API documentation:
509 https://doc.rust-lang.org/std/cell/
513 E0388 was removed and is no longer issued.
517 An attempt was made to mutate data using a non-mutable reference. This
518 commonly occurs when attempting to assign to a non-mutable reference of a
519 mutable reference (`&(&mut T)`).
521 Example of erroneous code:
523 ```compile_fail,E0389
529 let mut fancy = FancyNum{ num: 5 };
530 let fancy_ref = &(&mut fancy);
531 fancy_ref.num = 6; // error: cannot assign to data in a `&` reference
532 println!("{}", fancy_ref.num);
536 Here, `&mut fancy` is mutable, but `&(&mut fancy)` is not. Creating an
537 immutable reference to a value borrows it immutably. There can be multiple
538 references of type `&(&mut T)` that point to the same value, so they must be
539 immutable to prevent multiple mutable references to the same value.
541 To fix this, either remove the outer reference:
549 let mut fancy = FancyNum{ num: 5 };
551 let fancy_ref = &mut fancy;
552 // `fancy_ref` is now &mut FancyNum, rather than &(&mut FancyNum)
554 fancy_ref.num = 6; // No error!
556 println!("{}", fancy_ref.num);
560 Or make the outer reference mutable:
568 let mut fancy = FancyNum{ num: 5 };
570 let fancy_ref = &mut (&mut fancy);
571 // `fancy_ref` is now &mut(&mut FancyNum), rather than &(&mut FancyNum)
573 fancy_ref.num = 6; // No error!
575 println!("{}", fancy_ref.num);
581 A static was referred to by value by another static.
583 Erroneous code examples:
585 ```compile_fail,E0394
587 static B: u32 = A; // error: cannot refer to other statics by value, use the
588 // address-of operator or a constant instead
591 A static cannot be referred by value. To fix this issue, either use a
595 const A: u32 = 0; // `A` is now a constant
596 static B: u32 = A; // ok!
599 Or refer to `A` by reference:
603 static B: &'static u32 = &A; // ok!
608 The value assigned to a constant scalar must be known at compile time,
609 which is not the case when comparing raw pointers.
611 Erroneous code example:
613 ```compile_fail,E0395
614 static FOO: i32 = 42;
615 static BAR: i32 = 42;
617 static BAZ: bool = { (&FOO as *const i32) == (&BAR as *const i32) };
618 // error: raw pointers cannot be compared in statics!
621 The address assigned by the linker to `FOO` and `BAR` may or may not
622 be identical, so the value of `BAZ` can't be determined.
624 If you want to do the comparison, please do it at run-time.
629 static FOO: i32 = 42;
630 static BAR: i32 = 42;
632 let baz: bool = { (&FOO as *const i32) == (&BAR as *const i32) };
633 // baz isn't a constant expression so it's ok
638 A value was moved. However, its size was not known at compile time, and only
639 values of a known size can be moved.
641 Erroneous code example:
644 #![feature(box_syntax)]
647 let array: &[isize] = &[1, 2, 3];
648 let _x: Box<[isize]> = box *array;
649 // error: cannot move a value of type [isize]: the size of [isize] cannot
650 // be statically determined
654 In Rust, you can only move a value when its size is known at compile time.
656 To work around this restriction, consider "hiding" the value behind a reference:
657 either `&x` or `&mut x`. Since a reference has a fixed size, this lets you move
658 it around as usual. Example:
661 #![feature(box_syntax)]
664 let array: &[isize] = &[1, 2, 3];
665 let _x: Box<&[isize]> = box array; // ok!
671 The value behind a raw pointer can't be determined at compile-time
672 (or even link-time), which means it can't be used in a constant
673 expression. Erroneous code example:
675 ```compile_fail,E0396
676 const REG_ADDR: *const u8 = 0x5f3759df as *const u8;
678 const VALUE: u8 = unsafe { *REG_ADDR };
679 // error: raw pointers cannot be dereferenced in constants
682 A possible fix is to dereference your pointer at some point in run-time.
687 const REG_ADDR: *const u8 = 0x5f3759df as *const u8;
689 let reg_value = unsafe { *REG_ADDR };
694 A borrow of a constant containing interior mutability was attempted. Erroneous
697 ```compile_fail,E0492
698 use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT};
700 const A: AtomicUsize = ATOMIC_USIZE_INIT;
701 static B: &'static AtomicUsize = &A;
702 // error: cannot borrow a constant which may contain interior mutability,
703 // create a static instead
706 A `const` represents a constant value that should never change. If one takes
707 a `&` reference to the constant, then one is taking a pointer to some memory
708 location containing the value. Normally this is perfectly fine: most values
709 can't be changed via a shared `&` pointer, but interior mutability would allow
710 it. That is, a constant value could be mutated. On the other hand, a `static` is
711 explicitly a single memory location, which can be mutated at will.
713 So, in order to solve this error, either use statics which are `Sync`:
716 use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT};
718 static A: AtomicUsize = ATOMIC_USIZE_INIT;
719 static B: &'static AtomicUsize = &A; // ok!
722 You can also have this error while using a cell type:
724 ```compile_fail,E0492
725 #![feature(const_cell_new)]
729 const A: Cell<usize> = Cell::new(1);
730 const B: &'static Cell<usize> = &A;
731 // error: cannot borrow a constant which may contain interior mutability,
732 // create a static instead
735 struct C { a: Cell<usize> }
737 const D: C = C { a: Cell::new(1) };
738 const E: &'static Cell<usize> = &D.a; // error
741 const F: &'static C = &D; // error
744 This is because cell types do operations that are not thread-safe. Due to this,
745 they don't implement Sync and thus can't be placed in statics. In this
746 case, `StaticMutex` would work just fine, but it isn't stable yet:
747 https://doc.rust-lang.org/nightly/std/sync/struct.StaticMutex.html
749 However, if you still wish to use these types, you can achieve this by an unsafe
753 #![feature(const_cell_new)]
756 use std::marker::Sync;
758 struct NotThreadSafe<T> {
762 unsafe impl<T> Sync for NotThreadSafe<T> {}
764 static A: NotThreadSafe<usize> = NotThreadSafe { value : Cell::new(1) };
765 static B: &'static NotThreadSafe<usize> = &A; // ok!
768 Remember this solution is unsafe! You will have to ensure that accesses to the
769 cell are synchronized.
773 A reference of an interior static was assigned to another const/static.
774 Erroneous code example:
776 ```compile_fail,E0494
781 static S : Foo = Foo { a : 0 };
782 static A : &'static u32 = &S.a;
783 // error: cannot refer to the interior of another static, use a
787 The "base" variable has to be a const if you want another static/const variable
788 to refer to one of its fields. Example:
795 const S : Foo = Foo { a : 0 };
796 static A : &'static u32 = &S.a; // ok!
801 A variable was borrowed as mutable more than once. Erroneous code example:
803 ```compile_fail,E0499
807 // error: cannot borrow `i` as mutable more than once at a time
810 Please note that in rust, you can either have many immutable references, or one
811 mutable reference. Take a look at
812 https://doc.rust-lang.org/stable/book/references-and-borrowing.html for more
813 information. Example:
818 let mut x = &mut i; // ok!
823 let b = &i; // still ok!
824 let c = &i; // still ok!
829 A borrowed variable was used in another closure. Example of erroneous code:
832 fn you_know_nothing(jon_snow: &mut i32) {
833 let nights_watch = || {
837 *jon_snow = 3; // error: closure requires unique access to `jon_snow`
838 // but it is already borrowed
843 In here, `jon_snow` is already borrowed by the `nights_watch` closure, so it
844 cannot be borrowed by the `starks` closure at the same time. To fix this issue,
845 you can put the closure in its own scope:
848 fn you_know_nothing(jon_snow: &mut i32) {
850 let nights_watch = || {
853 } // At this point, `jon_snow` is free.
860 Or, if the type implements the `Clone` trait, you can clone it between
864 fn you_know_nothing(jon_snow: &mut i32) {
865 let mut jon_copy = jon_snow.clone();
866 let nights_watch = || {
877 This error indicates that a mutable variable is being used while it is still
878 captured by a closure. Because the closure has borrowed the variable, it is not
879 available for use until the closure goes out of scope.
881 Note that a capture will either move or borrow a variable, but in this
882 situation, the closure is borrowing the variable. Take a look at
883 http://rustbyexample.com/fn/closures/capture.html for more information about
886 Example of erroneous code:
888 ```compile_fail,E0501
889 fn inside_closure(x: &mut i32) {
890 // Actions which require unique access
893 fn outside_closure(x: &mut i32) {
894 // Actions which require unique access
897 fn foo(a: &mut i32) {
901 outside_closure(a); // error: cannot borrow `*a` as mutable because previous
902 // closure requires unique access.
906 To fix this error, you can place the closure in its own scope:
909 fn inside_closure(x: &mut i32) {}
910 fn outside_closure(x: &mut i32) {}
912 fn foo(a: &mut i32) {
917 } // borrow on `a` ends.
918 outside_closure(a); // ok!
922 Or you can pass the variable as a parameter to the closure:
925 fn inside_closure(x: &mut i32) {}
926 fn outside_closure(x: &mut i32) {}
928 fn foo(a: &mut i32) {
929 let bar = |s: &mut i32| {
937 It may be possible to define the closure later:
940 fn inside_closure(x: &mut i32) {}
941 fn outside_closure(x: &mut i32) {}
943 fn foo(a: &mut i32) {
953 This error indicates that you are trying to borrow a variable as mutable when it
954 has already been borrowed as immutable.
956 Example of erroneous code:
958 ```compile_fail,E0502
959 fn bar(x: &mut i32) {}
960 fn foo(a: &mut i32) {
961 let ref y = a; // a is borrowed as immutable.
962 bar(a); // error: cannot borrow `*a` as mutable because `a` is also borrowed
967 To fix this error, ensure that you don't have any other references to the
968 variable before trying to access it mutably:
971 fn bar(x: &mut i32) {}
972 fn foo(a: &mut i32) {
974 let ref y = a; // ok!
978 For more information on the rust ownership system, take a look at
979 https://doc.rust-lang.org/stable/book/references-and-borrowing.html.
983 A value was used after it was mutably borrowed.
985 Example of erroneous code:
987 ```compile_fail,E0503
990 // Create a mutable borrow of `value`. This borrow
991 // lives until the end of this function.
992 let _borrow = &mut value;
993 let _sum = value + 1; // error: cannot use `value` because
994 // it was mutably borrowed
998 In this example, `value` is mutably borrowed by `borrow` and cannot be
999 used to calculate `sum`. This is not possible because this would violate
1000 Rust's mutability rules.
1002 You can fix this error by limiting the scope of the borrow:
1007 // By creating a new block, you can limit the scope
1008 // of the reference.
1010 let _borrow = &mut value; // Use `_borrow` inside this block.
1012 // The block has ended and with it the borrow.
1013 // You can now use `value` again.
1014 let _sum = value + 1;
1018 Or by cloning `value` before borrowing it:
1023 // We clone `value`, creating a copy.
1024 let value_cloned = value.clone();
1025 // The mutable borrow is a reference to `value` and
1026 // not to `value_cloned`...
1027 let _borrow = &mut value;
1028 // ... which means we can still use `value_cloned`,
1029 let _sum = value_cloned + 1;
1030 // even though the borrow only ends here.
1034 You can find more information about borrowing in the rust-book:
1035 http://doc.rust-lang.org/stable/book/references-and-borrowing.html
1039 This error occurs when an attempt is made to move a borrowed variable into a
1042 Example of erroneous code:
1044 ```compile_fail,E0504
1050 let fancy_num = FancyNum { num: 5 };
1051 let fancy_ref = &fancy_num;
1054 println!("child function: {}", fancy_num.num);
1055 // error: cannot move `fancy_num` into closure because it is borrowed
1059 println!("main function: {}", fancy_ref.num);
1063 Here, `fancy_num` is borrowed by `fancy_ref` and so cannot be moved into
1064 the closure `x`. There is no way to move a value into a closure while it is
1065 borrowed, as that would invalidate the borrow.
1067 If the closure can't outlive the value being moved, try using a reference
1076 let fancy_num = FancyNum { num: 5 };
1077 let fancy_ref = &fancy_num;
1080 // fancy_ref is usable here because it doesn't move `fancy_num`
1081 println!("child function: {}", fancy_ref.num);
1086 println!("main function: {}", fancy_num.num);
1090 If the value has to be borrowed and then moved, try limiting the lifetime of
1091 the borrow using a scoped block:
1099 let fancy_num = FancyNum { num: 5 };
1102 let fancy_ref = &fancy_num;
1103 println!("main function: {}", fancy_ref.num);
1104 // `fancy_ref` goes out of scope here
1108 // `fancy_num` can be moved now (no more references exist)
1109 println!("child function: {}", fancy_num.num);
1116 If the lifetime of a reference isn't enough, such as in the case of threading,
1117 consider using an `Arc` to create a reference-counted value:
1128 let fancy_ref1 = Arc::new(FancyNum { num: 5 });
1129 let fancy_ref2 = fancy_ref1.clone();
1131 let x = thread::spawn(move || {
1132 // `fancy_ref1` can be moved and has a `'static` lifetime
1133 println!("child thread: {}", fancy_ref1.num);
1136 x.join().expect("child thread should finish");
1137 println!("main thread: {}", fancy_ref2.num);
1143 A value was moved out while it was still borrowed.
1145 Erroneous code example:
1147 ```compile_fail,E0505
1150 fn eat(val: Value) {}
1155 let _ref_to_val: &Value = &x;
1161 Here, the function `eat` takes the ownership of `x`. However,
1162 `x` cannot be moved because it was borrowed to `_ref_to_val`.
1163 To fix that you can do few different things:
1165 * Try to avoid moving the variable.
1166 * Release borrow before move.
1167 * Implement the `Copy` trait on the type.
1174 fn eat(val: &Value) {}
1179 let _ref_to_val: &Value = &x;
1180 eat(&x); // pass by reference, if it's possible
1190 fn eat(val: Value) {}
1195 let _ref_to_val: &Value = &x;
1197 eat(x); // release borrow and then move it.
1204 #[derive(Clone, Copy)] // implement Copy trait
1207 fn eat(val: Value) {}
1212 let _ref_to_val: &Value = &x;
1213 eat(x); // it will be copied here.
1218 You can find more information about borrowing in the rust-book:
1219 http://doc.rust-lang.org/stable/book/references-and-borrowing.html
1223 This error occurs when an attempt is made to assign to a borrowed value.
1225 Example of erroneous code:
1227 ```compile_fail,E0506
1233 let mut fancy_num = FancyNum { num: 5 };
1234 let fancy_ref = &fancy_num;
1235 fancy_num = FancyNum { num: 6 };
1236 // error: cannot assign to `fancy_num` because it is borrowed
1238 println!("Num: {}, Ref: {}", fancy_num.num, fancy_ref.num);
1242 Because `fancy_ref` still holds a reference to `fancy_num`, `fancy_num` can't
1243 be assigned to a new value as it would invalidate the reference.
1245 Alternatively, we can move out of `fancy_num` into a second `fancy_num`:
1253 let mut fancy_num = FancyNum { num: 5 };
1254 let moved_num = fancy_num;
1255 fancy_num = FancyNum { num: 6 };
1257 println!("Num: {}, Moved num: {}", fancy_num.num, moved_num.num);
1261 If the value has to be borrowed, try limiting the lifetime of the borrow using
1270 let mut fancy_num = FancyNum { num: 5 };
1273 let fancy_ref = &fancy_num;
1274 println!("Ref: {}", fancy_ref.num);
1277 // Works because `fancy_ref` is no longer in scope
1278 fancy_num = FancyNum { num: 6 };
1279 println!("Num: {}", fancy_num.num);
1283 Or by moving the reference into a function:
1291 let mut fancy_num = FancyNum { num: 5 };
1293 print_fancy_ref(&fancy_num);
1295 // Works because function borrow has ended
1296 fancy_num = FancyNum { num: 6 };
1297 println!("Num: {}", fancy_num.num);
1300 fn print_fancy_ref(fancy_ref: &FancyNum){
1301 println!("Ref: {}", fancy_ref.num);
1307 You tried to move out of a value which was borrowed. Erroneous code example:
1309 ```compile_fail,E0507
1310 use std::cell::RefCell;
1312 struct TheDarkKnight;
1314 impl TheDarkKnight {
1315 fn nothing_is_true(self) {}
1319 let x = RefCell::new(TheDarkKnight);
1321 x.borrow().nothing_is_true(); // error: cannot move out of borrowed content
1325 Here, the `nothing_is_true` method takes the ownership of `self`. However,
1326 `self` cannot be moved because `.borrow()` only provides an `&TheDarkKnight`,
1327 which is a borrow of the content owned by the `RefCell`. To fix this error,
1328 you have three choices:
1330 * Try to avoid moving the variable.
1331 * Somehow reclaim the ownership.
1332 * Implement the `Copy` trait on the type.
1337 use std::cell::RefCell;
1339 struct TheDarkKnight;
1341 impl TheDarkKnight {
1342 fn nothing_is_true(&self) {} // First case, we don't take ownership
1346 let x = RefCell::new(TheDarkKnight);
1348 x.borrow().nothing_is_true(); // ok!
1355 use std::cell::RefCell;
1357 struct TheDarkKnight;
1359 impl TheDarkKnight {
1360 fn nothing_is_true(self) {}
1364 let x = RefCell::new(TheDarkKnight);
1365 let x = x.into_inner(); // we get back ownership
1367 x.nothing_is_true(); // ok!
1374 use std::cell::RefCell;
1376 #[derive(Clone, Copy)] // we implement the Copy trait
1377 struct TheDarkKnight;
1379 impl TheDarkKnight {
1380 fn nothing_is_true(self) {}
1384 let x = RefCell::new(TheDarkKnight);
1386 x.borrow().nothing_is_true(); // ok!
1390 Moving a member out of a mutably borrowed struct will also cause E0507 error:
1392 ```compile_fail,E0507
1393 struct TheDarkKnight;
1395 impl TheDarkKnight {
1396 fn nothing_is_true(self) {}
1400 knight: TheDarkKnight
1404 let mut cave = Batcave {
1405 knight: TheDarkKnight
1407 let borrowed = &mut cave;
1409 borrowed.knight.nothing_is_true(); // E0507
1413 It is fine only if you put something back. `mem::replace` can be used for that:
1416 # struct TheDarkKnight;
1417 # impl TheDarkKnight { fn nothing_is_true(self) {} }
1418 # struct Batcave { knight: TheDarkKnight }
1421 let mut cave = Batcave {
1422 knight: TheDarkKnight
1424 let borrowed = &mut cave;
1426 mem::replace(&mut borrowed.knight, TheDarkKnight).nothing_is_true(); // ok!
1429 You can find more information about borrowing in the rust-book:
1430 http://doc.rust-lang.org/book/first-edition/references-and-borrowing.html
1434 A value was moved out of a non-copy fixed-size array.
1436 Example of erroneous code:
1438 ```compile_fail,E0508
1442 let array = [NonCopy; 1];
1443 let _value = array[0]; // error: cannot move out of type `[NonCopy; 1]`,
1444 // a non-copy fixed-size array
1448 The first element was moved out of the array, but this is not
1449 possible because `NonCopy` does not implement the `Copy` trait.
1451 Consider borrowing the element instead of moving it:
1457 let array = [NonCopy; 1];
1458 let _value = &array[0]; // Borrowing is allowed, unlike moving.
1462 Alternatively, if your type implements `Clone` and you need to own the value,
1463 consider borrowing and then cloning:
1470 let array = [NonCopy; 1];
1471 // Now you can clone the array element.
1472 let _value = array[0].clone();
1478 This error occurs when an attempt is made to move out of a value whose type
1479 implements the `Drop` trait.
1481 Example of erroneous code:
1483 ```compile_fail,E0509
1492 impl Drop for DropStruct {
1493 fn drop(&mut self) {
1494 // Destruct DropStruct, possibly using FancyNum
1499 let drop_struct = DropStruct{fancy: FancyNum{num: 5}};
1500 let fancy_field = drop_struct.fancy; // Error E0509
1501 println!("Fancy: {}", fancy_field.num);
1502 // implicit call to `drop_struct.drop()` as drop_struct goes out of scope
1506 Here, we tried to move a field out of a struct of type `DropStruct` which
1507 implements the `Drop` trait. However, a struct cannot be dropped if one or
1508 more of its fields have been moved.
1510 Structs implementing the `Drop` trait have an implicit destructor that gets
1511 called when they go out of scope. This destructor may use the fields of the
1512 struct, so moving out of the struct could make it impossible to run the
1513 destructor. Therefore, we must think of all values whose type implements the
1514 `Drop` trait as single units whose fields cannot be moved.
1516 This error can be fixed by creating a reference to the fields of a struct,
1517 enum, or tuple using the `ref` keyword:
1528 impl Drop for DropStruct {
1529 fn drop(&mut self) {
1530 // Destruct DropStruct, possibly using FancyNum
1535 let drop_struct = DropStruct{fancy: FancyNum{num: 5}};
1536 let ref fancy_field = drop_struct.fancy; // No more errors!
1537 println!("Fancy: {}", fancy_field.num);
1538 // implicit call to `drop_struct.drop()` as drop_struct goes out of scope
1542 Note that this technique can also be used in the arms of a match expression:
1553 impl Drop for DropEnum {
1554 fn drop(&mut self) {
1555 // Destruct DropEnum, possibly using FancyNum
1560 // Creates and enum of type `DropEnum`, which implements `Drop`
1561 let drop_enum = DropEnum::Fancy(FancyNum{num: 10});
1563 // Creates a reference to the inside of `DropEnum::Fancy`
1564 DropEnum::Fancy(ref fancy_field) => // No error!
1565 println!("It was fancy-- {}!", fancy_field.num),
1567 // implicit call to `drop_enum.drop()` as drop_enum goes out of scope
1573 Closures cannot mutate immutable captured variables.
1575 Erroneous code example:
1577 ```compile_fail,E0595
1578 let x = 3; // error: closure cannot assign to immutable local variable `x`
1579 let mut c = || { x += 1 };
1582 Make the variable binding mutable:
1585 let mut x = 3; // ok!
1586 let mut c = || { x += 1 };
1591 This error occurs because you tried to mutably borrow a non-mutable variable.
1593 Example of erroneous code:
1595 ```compile_fail,E0596
1597 let y = &mut x; // error: cannot borrow mutably
1600 In here, `x` isn't mutable, so when we try to mutably borrow it in `y`, it
1601 fails. To fix this error, you need to make `x` mutable:
1605 let y = &mut x; // ok!
1610 This error occurs because a borrow was made inside a variable which has a
1611 greater lifetime than the borrowed one.
1613 Example of erroneous code:
1615 ```compile_fail,E0597
1620 let mut x = Foo { x: None };
1622 x.x = Some(&y); // error: `y` does not live long enough
1625 In here, `x` is created before `y` and therefore has a greater lifetime. Always
1626 keep in mind that values in a scope are dropped in the opposite order they are
1627 created. So to fix the previous example, just make the `y` lifetime greater than
1636 let mut x = Foo { x: None };
1642 This error occurs because a borrow in a generator persists across a
1645 ```compile_fail,E0626
1646 # #![feature(generators, generator_trait)]
1647 # use std::ops::Generator;
1649 let a = &String::new(); // <-- This borrow...
1650 yield (); // ...is still in scope here, when the yield occurs.
1656 At present, it is not permitted to have a yield that occurs while a
1657 borrow is still in scope. To resolve this error, the borrow must
1658 either be "contained" to a smaller scope that does not overlap the
1659 yield or else eliminated in another way. So, for example, we might
1660 resolve the previous example by removing the borrow and just storing
1661 the integer by value:
1664 # #![feature(generators, generator_trait)]
1665 # use std::ops::Generator;
1674 This is a very simple case, of course. In more complex cases, we may
1675 wish to have more than one reference to the value that was borrowed --
1676 in those cases, something like the `Rc` or `Arc` types may be useful.
1678 This error also frequently arises with iteration:
1680 ```compile_fail,E0626
1681 # #![feature(generators, generator_trait)]
1682 # use std::ops::Generator;
1684 let v = vec![1,2,3];
1685 for &x in &v { // <-- borrow of `v` is still in scope...
1686 yield x; // ...when this yield occurs.
1692 Such cases can sometimes be resolved by iterating "by value" (or using
1693 `into_iter()`) to avoid borrowing:
1696 # #![feature(generators, generator_trait)]
1697 # use std::ops::Generator;
1699 let v = vec![1,2,3];
1700 for x in v { // <-- Take ownership of the values instead!
1701 yield x; // <-- Now yield is OK.
1707 If taking ownership is not an option, using indices can work too:
1710 # #![feature(generators, generator_trait)]
1711 # use std::ops::Generator;
1713 let v = vec![1,2,3];
1714 let len = v.len(); // (*)
1716 let x = v[i]; // (*)
1717 yield x; // <-- Now yield is OK.
1722 // (*) -- Unfortunately, these temporaries are currently required.
1723 // See <https://github.com/rust-lang/rust/issues/43122>.
1729 register_diagnostics! {
1730 // E0385, // {} in an aliasable location
1731 E0493, // destructors cannot be evaluated at compile-time
1732 E0524, // two closures require unique access to `..` at the same time
1733 E0526, // shuffle indices are not constant
1734 E0594, // cannot assign to {}
1735 E0598, // lifetime of {} is too short to guarantee its contents can be...
1736 E0625, // thread-local statics cannot be accessed at compile-time