]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/error_codes.rs
Update to use new librustc_error_codes library
[rust.git] / src / librustc_mir / error_codes.rs
1 syntax::register_diagnostics! {
2
3
4 E0001: r##"
5 #### Note: this error code is no longer emitted by the compiler.
6
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.
10
11 This means that perhaps some of the preceding patterns are too general, this
12 one is too specific or the ordering is incorrect.
13
14 For example, the following `match` block has too many arms:
15
16 ```
17 match Some(0) {
18     Some(bar) => {/* ... */}
19     x => {/* ... */} // This handles the `None` case
20     _ => {/* ... */} // All possible cases have already been handled
21 }
22 ```
23
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.
26
27 Ensure the ordering of the match arm is correct and remove any superfluous
28 arms.
29 "##,
30
31 E0002: r##"
32 #### Note: this error code is no longer emitted by the compiler.
33
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.
39
40 An example of an empty type is `enum Empty { }`. So, the following will work:
41
42 ```
43 enum Empty {}
44
45 fn foo(x: Empty) {
46     match x {
47         // empty
48     }
49 }
50 ```
51
52 However, this won't:
53
54 ```compile_fail
55 fn foo(x: Option<String>) {
56     match x {
57         // empty
58     }
59 }
60 ```
61 "##,
62
63 E0004: r##"
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.
68
69 Erroneous code example:
70
71 ```compile_fail,E0004
72 enum Terminator {
73     HastaLaVistaBaby,
74     TalkToMyHand,
75 }
76
77 let x = Terminator::HastaLaVistaBaby;
78
79 match x { // error: non-exhaustive patterns: `HastaLaVistaBaby` not covered
80     Terminator::TalkToMyHand => {}
81 }
82 ```
83
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:
89
90 ```
91 enum Terminator {
92     HastaLaVistaBaby,
93     TalkToMyHand,
94 }
95
96 let x = Terminator::HastaLaVistaBaby;
97
98 match x {
99     Terminator::TalkToMyHand => {}
100     Terminator::HastaLaVistaBaby => {}
101 }
102
103 // or:
104
105 match x {
106     Terminator::TalkToMyHand => {}
107     _ => {}
108 }
109 ```
110 "##,
111
112 E0005: r##"
113 Patterns used to bind names must be irrefutable, that is, they must guarantee
114 that a name will be extracted in all cases.
115
116 Erroneous code example:
117
118 ```compile_fail,E0005
119 let x = Some(1);
120 let Some(y) = x;
121 // error: refutable pattern in local binding: `None` not covered
122 ```
123
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:
126
127 ```
128 let x = Some(1);
129
130 match x {
131     Some(y) => {
132         // do something
133     },
134     None => {}
135 }
136
137 // or:
138
139 if let Some(y) = x {
140     // do something
141 }
142 ```
143 "##,
144
145 E0007: r##"
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`.
151
152 Erroneous code example:
153
154 ```compile_fail,E0007
155 let x = Some("s".to_string());
156
157 match x {
158     op_string @ Some(s) => {}, // error: cannot bind by-move with sub-bindings
159     None => {},
160 }
161 ```
162
163 See also the error E0303.
164 "##,
165
166 E0009: r##"
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
169 by-ref.
170
171 This limitation may be removed in a future version of Rust.
172
173 Erroneous code example:
174
175 ```compile_fail,E0009
176 struct X { x: (), }
177
178 let x = Some((X { x: () }, X { x: () }));
179 match x {
180     Some((y, ref z)) => {}, // error: cannot bind by-move and by-ref in the
181                             //        same pattern
182     None => panic!()
183 }
184 ```
185
186 You have two solutions:
187
188 Solution #1: Bind the pattern's values the same way.
189
190 ```
191 struct X { x: (), }
192
193 let x = Some((X { x: () }, X { x: () }));
194 match x {
195     Some((ref y, ref z)) => {},
196     // or Some((y, z)) => {}
197     None => panic!()
198 }
199 ```
200
201 Solution #2: Implement the `Copy` trait for the `X` structure.
202
203 However, please keep in mind that the first solution should be preferred.
204
205 ```
206 #[derive(Clone, Copy)]
207 struct X { x: (), }
208
209 let x = Some((X { x: () }, X { x: () }));
210 match x {
211     Some((y, ref z)) => {},
212     None => panic!()
213 }
214 ```
215 "##,
216
217 E0010: r##"
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.
221
222 Erroneous code example:
223
224 ```compile_fail,E0010
225 #![feature(box_syntax)]
226
227 const CON : Box<i32> = box 0;
228 ```
229 "##,
230
231 E0013: r##"
232 Static and const variables can refer to other const variables. But a const
233 variable cannot refer to a static variable.
234
235 Erroneous code example:
236
237 ```compile_fail,E0013
238 static X: i32 = 42;
239 const Y: i32 = X;
240 ```
241
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:
244
245 ```
246 const A: i32 = 42;
247 static X: i32 = A;
248 const Y: i32 = A;
249 ```
250 "##,
251
252 // FIXME(#57563) Change the language here when const fn stabilizes
253 E0015: r##"
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.
258
259 ```
260 const FOO: Option<u8> = Some(1); // enum constructor
261 struct Bar {x: u8}
262 const BAR: Bar = Bar {x: 1}; // struct constructor
263 ```
264
265 See [RFC 911] for more details on the design of `const fn`s.
266
267 [RFC 911]: https://github.com/rust-lang/rfcs/blob/master/text/0911-const-fn.md
268 "##,
269
270 E0017: r##"
271 References in statics and constants may only refer to immutable values.
272
273 Erroneous code example:
274
275 ```compile_fail,E0017
276 static X: i32 = 1;
277 const C: i32 = 2;
278
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;
283 ```
284
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
287 is not allowed.
288
289 If you really want global mutable state, try using `static mut` or a global
290 `UnsafeCell`.
291 "##,
292
293 E0019: r##"
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.
296
297 Erroneous code example:
298
299 ```compile_fail,E0019
300 #![feature(box_syntax)]
301
302 fn main() {
303     struct MyOwned;
304
305     static STATIC11: Box<MyOwned> = box MyOwned; // error!
306 }
307 ```
308
309 Remember: you can't use a function call inside a const's initialization
310 expression! However, you can totally use it anywhere else:
311
312 ```
313 enum Test {
314     V1
315 }
316
317 impl Test {
318     fn func(&self) -> i32 {
319         12
320     }
321 }
322
323 fn main() {
324     const FOO: Test = Test::V1;
325
326     FOO.func(); // here is good
327     let x = FOO.func(); // or even here!
328 }
329 ```
330 "##,
331
332 E0030: r##"
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
336 range.
337
338 Erroneous code example:
339
340 ```compile_fail,E0030
341 match 5u32 {
342     // This range is ok, albeit pointless.
343     1 ..= 1 => {}
344     // This range is empty, and the compiler can tell.
345     1000 ..= 5 => {}
346 }
347 ```
348 "##,
349
350 E0133: r##"
351 Unsafe code was used outside of an unsafe function or block.
352
353 Erroneous code example:
354
355 ```compile_fail,E0133
356 unsafe fn f() { return; } // This is the unsafe code
357
358 fn main() {
359     f(); // error: call to unsafe function requires unsafe function or block
360 }
361 ```
362
363 Using unsafe functionality is potentially dangerous and disallowed by safety
364 checks. Examples:
365
366 * Dereferencing raw pointers
367 * Calling functions via FFI
368 * Calling functions marked unsafe
369
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:
372
373 ```
374 unsafe fn f() { return; }
375
376 fn main() {
377     unsafe { f(); } // ok!
378 }
379 ```
380
381 See also https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html
382 "##,
383
384 E0158: r##"
385 An associated const has been referenced in a pattern.
386
387 Erroneous code example:
388
389 ```compile_fail,E0158
390 enum EFoo { A, B, C, D }
391
392 trait Foo {
393     const X: EFoo;
394 }
395
396 fn test<A: Foo>(arg: EFoo) {
397     match arg {
398         A::X => { // error!
399             println!("A::X");
400         }
401     }
402 }
403 ```
404
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.
408
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.
412
413 If you want to match against a `static`, consider using a guard instead:
414
415 ```
416 static FORTY_TWO: i32 = 42;
417
418 match Some(42) {
419     Some(x) if x == FORTY_TWO => {}
420     _ => {}
421 }
422 ```
423 "##,
424
425 E0161: r##"
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.
428
429 Erroneous code example:
430
431 ```compile_fail,E0161
432 #![feature(box_syntax)]
433
434 fn main() {
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
439 }
440 ```
441
442 In Rust, you can only move a value when its size is known at compile time.
443
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:
447
448 ```
449 #![feature(box_syntax)]
450
451 fn main() {
452     let array: &[isize] = &[1, 2, 3];
453     let _x: Box<&[isize]> = box array; // ok!
454 }
455 ```
456 "##,
457
458 E0162: r##"
459 #### Note: this error code is no longer emitted by the compiler.
460
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:
464
465 ```
466 struct Irrefutable(i32);
467 let irr = Irrefutable(0);
468
469 // This fails to compile because the match is irrefutable.
470 if let Irrefutable(x) = irr {
471     // This body will always be executed.
472     // ...
473 }
474 ```
475
476 Try this instead:
477
478 ```
479 struct Irrefutable(i32);
480 let irr = Irrefutable(0);
481
482 let Irrefutable(x) = irr;
483 println!("{}", x);
484 ```
485 "##,
486
487 E0165: r##"
488 #### Note: this error code is no longer emitted by the compiler.
489
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:
493
494 ```no_run
495 struct Irrefutable(i32);
496 let irr = Irrefutable(0);
497
498 // This fails to compile because the match is irrefutable.
499 while let Irrefutable(x) = irr {
500     // ...
501 }
502 ```
503
504 Try this instead:
505
506 ```no_run
507 struct Irrefutable(i32);
508 let irr = Irrefutable(0);
509
510 loop {
511     let Irrefutable(x) = irr;
512     // ...
513 }
514 ```
515 "##,
516
517 E0170: r##"
518 Enum variants are qualified by default. For example, given this type:
519
520 ```
521 enum Method {
522     GET,
523     POST,
524 }
525 ```
526
527 You would match it using:
528
529 ```
530 enum Method {
531     GET,
532     POST,
533 }
534
535 let m = Method::GET;
536
537 match m {
538     Method::GET => {},
539     Method::POST => {},
540 }
541 ```
542
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
545 that happens.
546
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:
549
550 ```
551 use Method::*;
552 enum Method { GET, POST }
553 # fn main() {}
554 ```
555
556 If you want others to be able to import variants from your module directly, use
557 `pub use`:
558
559 ```
560 pub use Method::*;
561 pub enum Method { GET, POST }
562 # fn main() {}
563 ```
564 "##,
565
566
567 E0297: r##"
568 #### Note: this error code is no longer emitted by the compiler.
569
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
573 instance:
574
575 ```compile_fail,E0005
576 let xs : Vec<Option<i32>> = vec![Some(1), None];
577
578 // This fails because `None` is not covered.
579 for Some(x) in xs {
580     // ...
581 }
582 ```
583
584 Match inside the loop instead:
585
586 ```
587 let xs : Vec<Option<i32>> = vec![Some(1), None];
588
589 for item in xs {
590     match item {
591         Some(x) => {},
592         None => {},
593     }
594 }
595 ```
596
597 Or use `if let`:
598
599 ```
600 let xs : Vec<Option<i32>> = vec![Some(1), None];
601
602 for item in xs {
603     if let Some(x) = item {
604         // ...
605     }
606 }
607 ```
608 "##,
609
610 E0301: r##"
611 #### Note: this error code is no longer emitted by the compiler.
612
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:
618
619 ```compile_fail,E0596
620 match Some(()) {
621     None => { },
622     option if option.take().is_none() => {
623         /* impossible, option is `Some` */
624     },
625     Some(_) => { } // When the previous match failed, the option became `None`.
626 }
627 ```
628 "##,
629
630 E0302: r##"
631 #### Note: this error code is no longer emitted by the compiler.
632
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
637 were allowed:
638
639 ```compile_fail,E0594
640 match Some(()) {
641     None => { },
642     option if { option = None; false } => { },
643     Some(_) => { } // When the previous match failed, the option became `None`.
644 }
645 ```
646 "##,
647
648 E0303: r##"
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.
652
653 Before:
654
655 ```compile_fail,E0303
656 match Some("hi".to_string()) {
657     ref op_string_ref @ Some(s) => {},
658     None => {},
659 }
660 ```
661
662 After:
663
664 ```
665 match Some("hi".to_string()) {
666     Some(ref s) => {
667         let op_string_ref = &Some(s);
668         // ...
669     },
670     None => {},
671 }
672 ```
673
674 The `op_string_ref` binding has type `&Option<&String>` in both cases.
675
676 See also https://github.com/rust-lang/rust/issues/14587
677 "##,
678
679 E0373: r##"
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
682 return a closure:
683
684 ```compile_fail,E0373
685 fn foo() -> Box<Fn(u32) -> u32> {
686     let x = 0u32;
687     Box::new(|y| x + y)
688 }
689 ```
690
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
694 unsafe.
695
696 Another situation where this might be encountered is when spawning threads:
697
698 ```compile_fail,E0373
699 fn foo() {
700     let x = 0u32;
701     let y = 1u32;
702
703     let thr = std::thread::spawn(|| {
704         x + y
705     });
706 }
707 ```
708
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.
714
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:
718
719 ```
720 fn foo() -> Box<Fn(u32) -> u32> {
721     let x = 0u32;
722     Box::new(move |y| x + y)
723 }
724 ```
725
726 Now that the closure has its own copy of the data, there's no need to worry
727 about safety.
728 "##,
729
730 E0381: r##"
731 It is not allowed to use or capture an uninitialized variable.
732
733 Erroneous code example:
734
735 ```compile_fail,E0381
736 fn main() {
737     let x: i32;
738     let y = x; // error, use of possibly-uninitialized variable
739 }
740 ```
741
742 To fix this, ensure that any declared variables are initialized before being
743 used. Example:
744
745 ```
746 fn main() {
747     let x: i32 = 0;
748     let y = x; // ok!
749 }
750 ```
751 "##,
752
753 E0382: r##"
754 This error occurs when an attempt is made to use a variable after its contents
755 have been moved elsewhere.
756
757 Erroneous code example:
758
759 ```compile_fail,E0382
760 struct MyStruct { s: u32 }
761
762 fn main() {
763     let mut x = MyStruct{ s: 5u32 };
764     let y = x;
765     x.s = 6;
766     println!("{}", x.s);
767 }
768 ```
769
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.
773
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.
778
779 ```
780 fn main() {
781     let s1 = String::from("hello");
782
783     let len = calculate_length(&s1);
784
785     println!("The length of '{}' is {}.", s1, len);
786 }
787
788 fn calculate_length(s: &String) -> usize {
789     s.len()
790 }
791 ```
792
793 A mutable reference can be created with `&mut`.
794
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.
798
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.
803
804 ```
805 fn main() {
806     let mut s1 = String::from("many");
807     let s2 = s1.clone();
808     s1.remove(0);
809     println!("{} {}", s1, s2);
810 }
811 ```
812
813 If we control the definition of a type, we can implement `Clone` on it ourselves
814 with `#[derive(Clone)]`.
815
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`.
821
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.
825
826 ```
827 #[derive(Copy, Clone)]
828 struct Point { x: i32, y: i32 }
829
830 fn main() {
831     let mut p1 = Point{ x: -1, y: 2 };
832     let p2 = p1;
833     p1.x = 1;
834     println!("p1: {}, {}", p1.x, p1.y);
835     println!("p2: {}, {}", p2.x, p2.y);
836 }
837 ```
838
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`:
841
842 ```
843 use std::cell::RefCell;
844 use std::rc::Rc;
845
846 struct MyStruct { s: u32 }
847
848 fn main() {
849     let mut x = Rc::new(RefCell::new(MyStruct{ s: 5u32 }));
850     let y = x.clone();
851     x.borrow_mut().s = 6;
852     println!("{}", x.borrow().s);
853 }
854 ```
855
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.
859
860 If you wish to learn more about ownership in Rust, start with the chapter in the
861 Book:
862
863 https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html
864 "##,
865
866 E0383: r##"
867 #### Note: this error code is no longer emitted by the compiler.
868
869 This error occurs when an attempt is made to partially reinitialize a
870 structure that is currently uninitialized.
871
872 For example, this can happen when a drop has taken place:
873
874 ```compile_fail
875 struct Foo {
876     a: u32,
877 }
878 impl Drop for Foo {
879     fn drop(&mut self) { /* ... */ }
880 }
881
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`
885 ```
886
887 This error can be fixed by fully reinitializing the structure in question:
888
889 ```
890 struct Foo {
891     a: u32,
892 }
893 impl Drop for Foo {
894     fn drop(&mut self) { /* ... */ }
895 }
896
897 let mut x = Foo { a: 1 };
898 drop(x);
899 x = Foo { a: 2 };
900 ```
901 "##,
902
903 E0384: r##"
904 This error occurs when an attempt is made to reassign an immutable variable.
905
906 Erroneous code example:
907
908 ```compile_fail,E0384
909 fn main() {
910     let x = 3;
911     x = 5; // error, reassignment of immutable variable
912 }
913 ```
914
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:
917
918 ```
919 fn main() {
920     let mut x = 3;
921     x = 5;
922 }
923 ```
924 "##,
925
926 E0386: r##"
927 #### Note: this error code is no longer emitted by the compiler.
928
929 This error occurs when an attempt is made to mutate the target of a mutable
930 reference stored inside an immutable container.
931
932 For example, this can happen when storing a `&mut` inside an immutable `Box`:
933
934 ```
935 let mut x: i64 = 1;
936 let y: Box<_> = Box::new(&mut x);
937 **y = 2; // error, cannot assign to data in an immutable container
938 ```
939
940 This error can be fixed by making the container mutable:
941
942 ```
943 let mut x: i64 = 1;
944 let mut y: Box<_> = Box::new(&mut x);
945 **y = 2;
946 ```
947
948 It can also be fixed by using a type with interior mutability, such as `Cell`
949 or `RefCell`:
950
951 ```
952 use std::cell::Cell;
953
954 let x: i64 = 1;
955 let y: Box<Cell<_>> = Box::new(Cell::new(x));
956 y.set(2);
957 ```
958 "##,
959
960 E0387: r##"
961 #### Note: this error code is no longer emitted by the compiler.
962
963 This error occurs when an attempt is made to mutate or mutably reference data
964 that a closure has captured immutably.
965
966 Erroneous code example:
967
968 ```compile_fail
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) { }
972
973 // Attempts to mutate closed-over data. Error message reads:
974 // `cannot assign to data in a captured outer variable...`
975 fn mutable() {
976     let mut x = 0u32;
977     foo(|| x = 2);
978 }
979
980 // Attempts to take a mutable reference to closed-over data.  Error message
981 // reads: `cannot borrow data mutably in a captured outer variable...`
982 fn mut_addr() {
983     let mut x = 0u32;
984     foo(|| { let y = &mut x; });
985 }
986 ```
987
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.
991
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
994 rather than Fn:
995
996 ```
997 fn foo<F: FnMut()>(f: F) { }
998 ```
999
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:
1003
1004 ```
1005 use std::cell::Cell;
1006
1007 fn foo<F: Fn()>(f: F) { }
1008
1009 fn mutable() {
1010     let x = Cell::new(0u32);
1011     foo(|| x.set(2));
1012 }
1013 ```
1014
1015 You can read more about cell types in the API documentation:
1016
1017 https://doc.rust-lang.org/std/cell/
1018 "##,
1019
1020 E0388: r##"
1021 #### Note: this error code is no longer emitted by the compiler.
1022 "##,
1023
1024 E0389: r##"
1025 #### Note: this error code is no longer emitted by the compiler.
1026
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)`).
1030
1031 Erroneous code example:
1032
1033 ```compile_fail
1034 struct FancyNum {
1035     num: u8,
1036 }
1037
1038 fn main() {
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);
1043 }
1044 ```
1045
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.
1050
1051 To fix this, either remove the outer reference:
1052
1053 ```
1054 struct FancyNum {
1055     num: u8,
1056 }
1057
1058 fn main() {
1059     let mut fancy = FancyNum{ num: 5 };
1060
1061     let fancy_ref = &mut fancy;
1062     // `fancy_ref` is now &mut FancyNum, rather than &(&mut FancyNum)
1063
1064     fancy_ref.num = 6; // No error!
1065
1066     println!("{}", fancy_ref.num);
1067 }
1068 ```
1069
1070 Or make the outer reference mutable:
1071
1072 ```
1073 struct FancyNum {
1074     num: u8
1075 }
1076
1077 fn main() {
1078     let mut fancy = FancyNum{ num: 5 };
1079
1080     let fancy_ref = &mut (&mut fancy);
1081     // `fancy_ref` is now &mut(&mut FancyNum), rather than &(&mut FancyNum)
1082
1083     fancy_ref.num = 6; // No error!
1084
1085     println!("{}", fancy_ref.num);
1086 }
1087 ```
1088 "##,
1089
1090 E0492: r##"
1091 A borrow of a constant containing interior mutability was attempted.
1092
1093 Erroneous code example:
1094
1095 ```compile_fail,E0492
1096 use std::sync::atomic::AtomicUsize;
1097
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
1102 ```
1103
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.
1110
1111 So, in order to solve this error, either use statics which are `Sync`:
1112
1113 ```
1114 use std::sync::atomic::AtomicUsize;
1115
1116 static A: AtomicUsize = AtomicUsize::new(0);
1117 static B: &'static AtomicUsize = &A; // ok!
1118 ```
1119
1120 You can also have this error while using a cell type:
1121
1122 ```compile_fail,E0492
1123 use std::cell::Cell;
1124
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
1129
1130 // or:
1131 struct C { a: Cell<usize> }
1132
1133 const D: C = C { a: Cell::new(1) };
1134 const E: &Cell<usize> = &D.a; // error
1135
1136 // or:
1137 const F: &C = &D; // error
1138 ```
1139
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.
1142
1143 However, if you still wish to use these types, you can achieve this by an unsafe
1144 wrapper:
1145
1146 ```
1147 use std::cell::Cell;
1148 use std::marker::Sync;
1149
1150 struct NotThreadSafe<T> {
1151     value: Cell<T>,
1152 }
1153
1154 unsafe impl<T> Sync for NotThreadSafe<T> {}
1155
1156 static A: NotThreadSafe<usize> = NotThreadSafe { value : Cell::new(1) };
1157 static B: &'static NotThreadSafe<usize> = &A; // ok!
1158 ```
1159
1160 Remember this solution is unsafe! You will have to ensure that accesses to the
1161 cell are synchronized.
1162 "##,
1163
1164 E0493: r##"
1165 A type with a `Drop` implementation was destructured when trying to initialize
1166 a static item.
1167
1168 Erroneous code example:
1169
1170 ```compile_fail,E0493
1171 enum DropType {
1172     A,
1173 }
1174
1175 impl Drop for DropType {
1176     fn drop(&mut self) {}
1177 }
1178
1179 struct Foo {
1180     field1: DropType,
1181 }
1182
1183 static FOO: Foo = Foo { ..Foo { field1: DropType::A } }; // error!
1184 ```
1185
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.
1190
1191 ```
1192 enum DropType {
1193     A,
1194 }
1195
1196 impl Drop for DropType {
1197     fn drop(&mut self) {}
1198 }
1199
1200 struct Foo {
1201     field1: DropType,
1202 }
1203
1204 static FOO: Foo = Foo { field1: DropType::A }; // We initialize all fields
1205                                                // by hand.
1206 ```
1207 "##,
1208
1209 E0499: r##"
1210 A variable was borrowed as mutable more than once.
1211
1212 Erroneous code example:
1213
1214 ```compile_fail,E0499
1215 let mut i = 0;
1216 let mut x = &mut i;
1217 let mut a = &mut i;
1218 x;
1219 // error: cannot borrow `i` as mutable more than once at a time
1220 ```
1221
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:
1226
1227
1228 ```
1229 let mut i = 0;
1230 let mut x = &mut i; // ok!
1231
1232 // or:
1233 let mut i = 0;
1234 let a = &i; // ok!
1235 let b = &i; // still ok!
1236 let c = &i; // still ok!
1237 b;
1238 a;
1239 ```
1240 "##,
1241
1242 E0500: r##"
1243 A borrowed variable was used by a closure.
1244
1245 Erroneous code example:
1246
1247 ```compile_fail,E0500
1248 fn you_know_nothing(jon_snow: &mut i32) {
1249     let nights_watch = &jon_snow;
1250     let starks = || {
1251         *jon_snow = 3; // error: closure requires unique access to `jon_snow`
1252                        //        but it is already borrowed
1253     };
1254     println!("{}", nights_watch);
1255 }
1256 ```
1257
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:
1261
1262 ```
1263 fn you_know_nothing(jon_snow: &mut i32) {
1264     let nights_watch = &jon_snow;
1265     println!("{}", nights_watch);
1266     let starks = || {
1267         *jon_snow = 3;
1268     };
1269 }
1270 ```
1271
1272 Or, if the type implements the `Clone` trait, you can clone it between
1273 closures:
1274
1275 ```
1276 fn you_know_nothing(jon_snow: &mut i32) {
1277     let mut jon_copy = jon_snow.clone();
1278     let starks = || {
1279         *jon_snow = 3;
1280     };
1281     println!("{}", jon_copy);
1282 }
1283 ```
1284 "##,
1285
1286 E0501: r##"
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.
1290
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
1294 capturing.
1295
1296 Erroneous code example:
1297
1298 ```compile_fail,E0501
1299 fn inside_closure(x: &mut i32) {
1300     // Actions which require unique access
1301 }
1302
1303 fn outside_closure(x: &mut i32) {
1304     // Actions which require unique access
1305 }
1306
1307 fn foo(a: &mut i32) {
1308     let mut bar = || {
1309         inside_closure(a)
1310     };
1311     outside_closure(a); // error: cannot borrow `*a` as mutable because previous
1312                         //        closure requires unique access.
1313     bar();
1314 }
1315 ```
1316
1317 To fix this error, you can finish using the closure before using the captured
1318 variable:
1319
1320 ```
1321 fn inside_closure(x: &mut i32) {}
1322 fn outside_closure(x: &mut i32) {}
1323
1324 fn foo(a: &mut i32) {
1325     let mut bar = || {
1326         inside_closure(a)
1327     };
1328     bar();
1329     // borrow on `a` ends.
1330     outside_closure(a); // ok!
1331 }
1332 ```
1333
1334 Or you can pass the variable as a parameter to the closure:
1335
1336 ```
1337 fn inside_closure(x: &mut i32) {}
1338 fn outside_closure(x: &mut i32) {}
1339
1340 fn foo(a: &mut i32) {
1341     let mut bar = |s: &mut i32| {
1342         inside_closure(s)
1343     };
1344     outside_closure(a);
1345     bar(a);
1346 }
1347 ```
1348
1349 It may be possible to define the closure later:
1350
1351 ```
1352 fn inside_closure(x: &mut i32) {}
1353 fn outside_closure(x: &mut i32) {}
1354
1355 fn foo(a: &mut i32) {
1356     outside_closure(a);
1357     let mut bar = || {
1358         inside_closure(a)
1359     };
1360     bar();
1361 }
1362 ```
1363 "##,
1364
1365 E0502: r##"
1366 This error indicates that you are trying to borrow a variable as mutable when it
1367 has already been borrowed as immutable.
1368
1369 Erroneous code example:
1370
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
1376             //        as immutable
1377     println!("{}", y);
1378 }
1379 ```
1380
1381 To fix this error, ensure that you don't have any other references to the
1382 variable before trying to access it mutably:
1383
1384 ```
1385 fn bar(x: &mut i32) {}
1386 fn foo(a: &mut i32) {
1387     bar(a);
1388     let ref y = a; // ok!
1389     println!("{}", y);
1390 }
1391 ```
1392
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.
1395 "##,
1396
1397 E0503: r##"
1398 A value was used after it was mutably borrowed.
1399
1400 Erroneous code example:
1401
1402 ```compile_fail,E0503
1403 fn main() {
1404     let mut value = 3;
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);
1410 }
1411 ```
1412
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.
1416
1417 You can fix this error by finishing using the borrow before the next use of
1418 the value:
1419
1420 ```
1421 fn main() {
1422     let mut value = 3;
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;
1428 }
1429 ```
1430
1431 Or by cloning `value` before borrowing it:
1432
1433 ```
1434 fn main() {
1435     let mut value = 3;
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);
1445 }
1446 ```
1447
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
1450 "##,
1451
1452 E0504: r##"
1453 #### Note: this error code is no longer emitted by the compiler.
1454
1455 This error occurs when an attempt is made to move a borrowed variable into a
1456 closure.
1457
1458 Erroneous code example:
1459
1460 ```compile_fail
1461 struct FancyNum {
1462     num: u8,
1463 }
1464
1465 fn main() {
1466     let fancy_num = FancyNum { num: 5 };
1467     let fancy_ref = &fancy_num;
1468
1469     let x = move || {
1470         println!("child function: {}", fancy_num.num);
1471         // error: cannot move `fancy_num` into closure because it is borrowed
1472     };
1473
1474     x();
1475     println!("main function: {}", fancy_ref.num);
1476 }
1477 ```
1478
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.
1482
1483 If the closure can't outlive the value being moved, try using a reference
1484 rather than moving:
1485
1486 ```
1487 struct FancyNum {
1488     num: u8,
1489 }
1490
1491 fn main() {
1492     let fancy_num = FancyNum { num: 5 };
1493     let fancy_ref = &fancy_num;
1494
1495     let x = move || {
1496         // fancy_ref is usable here because it doesn't move `fancy_num`
1497         println!("child function: {}", fancy_ref.num);
1498     };
1499
1500     x();
1501
1502     println!("main function: {}", fancy_num.num);
1503 }
1504 ```
1505
1506 If the value has to be borrowed and then moved, try limiting the lifetime of
1507 the borrow using a scoped block:
1508
1509 ```
1510 struct FancyNum {
1511     num: u8,
1512 }
1513
1514 fn main() {
1515     let fancy_num = FancyNum { num: 5 };
1516
1517     {
1518         let fancy_ref = &fancy_num;
1519         println!("main function: {}", fancy_ref.num);
1520         // `fancy_ref` goes out of scope here
1521     }
1522
1523     let x = move || {
1524         // `fancy_num` can be moved now (no more references exist)
1525         println!("child function: {}", fancy_num.num);
1526     };
1527
1528     x();
1529 }
1530 ```
1531
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:
1534
1535 ```
1536 use std::sync::Arc;
1537 use std::thread;
1538
1539 struct FancyNum {
1540     num: u8,
1541 }
1542
1543 fn main() {
1544     let fancy_ref1 = Arc::new(FancyNum { num: 5 });
1545     let fancy_ref2 = fancy_ref1.clone();
1546
1547     let x = thread::spawn(move || {
1548         // `fancy_ref1` can be moved and has a `'static` lifetime
1549         println!("child thread: {}", fancy_ref1.num);
1550     });
1551
1552     x.join().expect("child thread should finish");
1553     println!("main thread: {}", fancy_ref2.num);
1554 }
1555 ```
1556 "##,
1557
1558 E0505: r##"
1559 A value was moved out while it was still borrowed.
1560
1561 Erroneous code example:
1562
1563 ```compile_fail,E0505
1564 struct Value {}
1565
1566 fn borrow(val: &Value) {}
1567
1568 fn eat(val: Value) {}
1569
1570 fn main() {
1571     let x = Value{};
1572     let _ref_to_val: &Value = &x;
1573     eat(x);
1574     borrow(_ref_to_val);
1575 }
1576 ```
1577
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:
1582
1583 * Try to avoid moving the variable.
1584 * Release borrow before move.
1585 * Implement the `Copy` trait on the type.
1586
1587 Examples:
1588
1589 ```
1590 struct Value {}
1591
1592 fn borrow(val: &Value) {}
1593
1594 fn eat(val: &Value) {}
1595
1596 fn main() {
1597     let x = Value{};
1598
1599     let ref_to_val: &Value = &x;
1600     eat(&x); // pass by reference, if it's possible
1601     borrow(ref_to_val);
1602 }
1603 ```
1604
1605 Or:
1606
1607 ```
1608 struct Value {}
1609
1610 fn borrow(val: &Value) {}
1611
1612 fn eat(val: Value) {}
1613
1614 fn main() {
1615     let x = Value{};
1616
1617     let ref_to_val: &Value = &x;
1618     borrow(ref_to_val);
1619     // ref_to_val is no longer used.
1620     eat(x);
1621 }
1622 ```
1623
1624 Or:
1625
1626 ```
1627 #[derive(Clone, Copy)] // implement Copy trait
1628 struct Value {}
1629
1630 fn borrow(val: &Value) {}
1631
1632 fn eat(val: Value) {}
1633
1634 fn main() {
1635     let x = Value{};
1636     let ref_to_val: &Value = &x;
1637     eat(x); // it will be copied here.
1638     borrow(ref_to_val);
1639 }
1640 ```
1641
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
1644 "##,
1645
1646 E0506: r##"
1647 This error occurs when an attempt is made to assign to a borrowed value.
1648
1649 Erroneous code example:
1650
1651 ```compile_fail,E0506
1652 struct FancyNum {
1653     num: u8,
1654 }
1655
1656 fn main() {
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
1661
1662     println!("Num: {}, Ref: {}", fancy_num.num, fancy_ref.num);
1663 }
1664 ```
1665
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.
1668
1669 Alternatively, we can move out of `fancy_num` into a second `fancy_num`:
1670
1671 ```
1672 struct FancyNum {
1673     num: u8,
1674 }
1675
1676 fn main() {
1677     let mut fancy_num = FancyNum { num: 5 };
1678     let moved_num = fancy_num;
1679     fancy_num = FancyNum { num: 6 };
1680
1681     println!("Num: {}, Moved num: {}", fancy_num.num, moved_num.num);
1682 }
1683 ```
1684
1685 If the value has to be borrowed, try limiting the lifetime of the borrow using
1686 a scoped block:
1687
1688 ```
1689 struct FancyNum {
1690     num: u8,
1691 }
1692
1693 fn main() {
1694     let mut fancy_num = FancyNum { num: 5 };
1695
1696     {
1697         let fancy_ref = &fancy_num;
1698         println!("Ref: {}", fancy_ref.num);
1699     }
1700
1701     // Works because `fancy_ref` is no longer in scope
1702     fancy_num = FancyNum { num: 6 };
1703     println!("Num: {}", fancy_num.num);
1704 }
1705 ```
1706
1707 Or by moving the reference into a function:
1708
1709 ```
1710 struct FancyNum {
1711     num: u8,
1712 }
1713
1714 fn main() {
1715     let mut fancy_num = FancyNum { num: 5 };
1716
1717     print_fancy_ref(&fancy_num);
1718
1719     // Works because function borrow has ended
1720     fancy_num = FancyNum { num: 6 };
1721     println!("Num: {}", fancy_num.num);
1722 }
1723
1724 fn print_fancy_ref(fancy_ref: &FancyNum){
1725     println!("Ref: {}", fancy_ref.num);
1726 }
1727 ```
1728 "##,
1729
1730 E0507: r##"
1731 You tried to move out of a value which was borrowed.
1732
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`
1736 closure bodies.
1737
1738 Erroneous code example:
1739
1740 ```compile_fail,E0507
1741 use std::cell::RefCell;
1742
1743 struct TheDarkKnight;
1744
1745 impl TheDarkKnight {
1746     fn nothing_is_true(self) {}
1747 }
1748
1749 fn main() {
1750     let x = RefCell::new(TheDarkKnight);
1751
1752     x.borrow().nothing_is_true(); // error: cannot move out of borrowed content
1753 }
1754 ```
1755
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:
1760
1761 * Try to avoid moving the variable.
1762 * Somehow reclaim the ownership.
1763 * Implement the `Copy` trait on the type.
1764
1765 Examples:
1766
1767 ```
1768 use std::cell::RefCell;
1769
1770 struct TheDarkKnight;
1771
1772 impl TheDarkKnight {
1773     fn nothing_is_true(&self) {} // First case, we don't take ownership
1774 }
1775
1776 fn main() {
1777     let x = RefCell::new(TheDarkKnight);
1778
1779     x.borrow().nothing_is_true(); // ok!
1780 }
1781 ```
1782
1783 Or:
1784
1785 ```
1786 use std::cell::RefCell;
1787
1788 struct TheDarkKnight;
1789
1790 impl TheDarkKnight {
1791     fn nothing_is_true(self) {}
1792 }
1793
1794 fn main() {
1795     let x = RefCell::new(TheDarkKnight);
1796     let x = x.into_inner(); // we get back ownership
1797
1798     x.nothing_is_true(); // ok!
1799 }
1800 ```
1801
1802 Or:
1803
1804 ```
1805 use std::cell::RefCell;
1806
1807 #[derive(Clone, Copy)] // we implement the Copy trait
1808 struct TheDarkKnight;
1809
1810 impl TheDarkKnight {
1811     fn nothing_is_true(self) {}
1812 }
1813
1814 fn main() {
1815     let x = RefCell::new(TheDarkKnight);
1816
1817     x.borrow().nothing_is_true(); // ok!
1818 }
1819 ```
1820
1821 Moving a member out of a mutably borrowed struct will also cause E0507 error:
1822
1823 ```compile_fail,E0507
1824 struct TheDarkKnight;
1825
1826 impl TheDarkKnight {
1827     fn nothing_is_true(self) {}
1828 }
1829
1830 struct Batcave {
1831     knight: TheDarkKnight
1832 }
1833
1834 fn main() {
1835     let mut cave = Batcave {
1836         knight: TheDarkKnight
1837     };
1838     let borrowed = &mut cave;
1839
1840     borrowed.knight.nothing_is_true(); // E0507
1841 }
1842 ```
1843
1844 It is fine only if you put something back. `mem::replace` can be used for that:
1845
1846 ```
1847 # struct TheDarkKnight;
1848 # impl TheDarkKnight { fn nothing_is_true(self) {} }
1849 # struct Batcave { knight: TheDarkKnight }
1850 use std::mem;
1851
1852 let mut cave = Batcave {
1853     knight: TheDarkKnight
1854 };
1855 let borrowed = &mut cave;
1856
1857 mem::replace(&mut borrowed.knight, TheDarkKnight).nothing_is_true(); // ok!
1858 ```
1859
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
1862 "##,
1863
1864 E0508: r##"
1865 A value was moved out of a non-copy fixed-size array.
1866
1867 Erroneous code example:
1868
1869 ```compile_fail,E0508
1870 struct NonCopy;
1871
1872 fn main() {
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
1876 }
1877 ```
1878
1879 The first element was moved out of the array, but this is not
1880 possible because `NonCopy` does not implement the `Copy` trait.
1881
1882 Consider borrowing the element instead of moving it:
1883
1884 ```
1885 struct NonCopy;
1886
1887 fn main() {
1888     let array = [NonCopy; 1];
1889     let _value = &array[0]; // Borrowing is allowed, unlike moving.
1890 }
1891 ```
1892
1893 Alternatively, if your type implements `Clone` and you need to own the value,
1894 consider borrowing and then cloning:
1895
1896 ```
1897 #[derive(Clone)]
1898 struct NonCopy;
1899
1900 fn main() {
1901     let array = [NonCopy; 1];
1902     // Now you can clone the array element.
1903     let _value = array[0].clone();
1904 }
1905 ```
1906 "##,
1907
1908 E0509: r##"
1909 This error occurs when an attempt is made to move out of a value whose type
1910 implements the `Drop` trait.
1911
1912 Erroneous code example:
1913
1914 ```compile_fail,E0509
1915 struct FancyNum {
1916     num: usize
1917 }
1918
1919 struct DropStruct {
1920     fancy: FancyNum
1921 }
1922
1923 impl Drop for DropStruct {
1924     fn drop(&mut self) {
1925         // Destruct DropStruct, possibly using FancyNum
1926     }
1927 }
1928
1929 fn main() {
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
1934 }
1935 ```
1936
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.
1940
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.
1946
1947 This error can be fixed by creating a reference to the fields of a struct,
1948 enum, or tuple using the `ref` keyword:
1949
1950 ```
1951 struct FancyNum {
1952     num: usize
1953 }
1954
1955 struct DropStruct {
1956     fancy: FancyNum
1957 }
1958
1959 impl Drop for DropStruct {
1960     fn drop(&mut self) {
1961         // Destruct DropStruct, possibly using FancyNum
1962     }
1963 }
1964
1965 fn main() {
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
1970 }
1971 ```
1972
1973 Note that this technique can also be used in the arms of a match expression:
1974
1975 ```
1976 struct FancyNum {
1977     num: usize
1978 }
1979
1980 enum DropEnum {
1981     Fancy(FancyNum)
1982 }
1983
1984 impl Drop for DropEnum {
1985     fn drop(&mut self) {
1986         // Destruct DropEnum, possibly using FancyNum
1987     }
1988 }
1989
1990 fn main() {
1991     // Creates and enum of type `DropEnum`, which implements `Drop`
1992     let drop_enum = DropEnum::Fancy(FancyNum{num: 10});
1993     match drop_enum {
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),
1997     }
1998     // implicit call to `drop_enum.drop()` as drop_enum goes out of scope
1999 }
2000 ```
2001 "##,
2002
2003 E0510: r##"
2004 Cannot mutate place in this match guard.
2005
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:
2008
2009 ```compile_fail,E0510
2010 let mut x = Some(0);
2011 match x {
2012     None => (),
2013     Some(_) if { x = None; false } => (),
2014     Some(v) => (), // No longer matches
2015 }
2016 ```
2017
2018 Here executing `x = None` would modify the value being matched and require us
2019 to go "back in time" to the `None` arm.
2020 "##,
2021
2022 E0515: r##"
2023 Cannot return value that references local variable
2024
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.
2027
2028 Erroneous code example:
2029
2030 ```compile_fail,E0515
2031 fn get_dangling_reference() -> &'static i32 {
2032     let x = 0;
2033     &x
2034 }
2035 ```
2036
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];
2041     v.iter()
2042 }
2043 ```
2044
2045 Consider returning an owned value instead:
2046
2047 ```
2048 use std::vec::IntoIter;
2049
2050 fn get_integer() -> i32 {
2051     let x = 0;
2052     x
2053 }
2054
2055 fn get_owned_iterator() -> IntoIter<i32> {
2056     let v = vec![1, 2, 3];
2057     v.into_iter()
2058 }
2059 ```
2060 "##,
2061
2062 E0524: r##"
2063 A variable which requires unique access is being used in more than one closure
2064 at the same time.
2065
2066 Erroneous code example:
2067
2068 ```compile_fail,E0524
2069 fn set(x: &mut isize) {
2070     *x += 4;
2071 }
2072
2073 fn dragoooon(x: &mut isize) {
2074     let mut c1 = || set(x);
2075     let mut c2 = || set(x); // error!
2076
2077     c2();
2078     c1();
2079 }
2080 ```
2081
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
2085 concurrently):
2086
2087 ```
2088 use std::rc::Rc;
2089 use std::cell::RefCell;
2090
2091 fn set(x: &mut isize) {
2092     *x += 4;
2093 }
2094
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!
2100
2101     c2();
2102     c1();
2103 }
2104 ```
2105
2106 If not, just run closures one at a time:
2107
2108 ```
2109 fn set(x: &mut isize) {
2110     *x += 4;
2111 }
2112
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);
2117         c1();
2118     } // `c1` has been dropped here so we're free to use `x` again!
2119     let mut c2 = || set(&mut *x);
2120     c2();
2121 }
2122 ```
2123 "##,
2124
2125 E0579: r##"
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.
2130
2131 Erroneous code example:
2132
2133 ```compile_fail,E0579
2134 #![feature(exclusive_range_pattern)]
2135
2136 fn main() {
2137     match 5u32 {
2138         // This range is ok, albeit pointless.
2139         1 .. 2 => {}
2140         // This range is empty, and the compiler can tell.
2141         5 .. 5 => {} // error!
2142     }
2143 }
2144 ```
2145 "##,
2146
2147 E0595: r##"
2148 #### Note: this error code is no longer emitted by the compiler.
2149
2150 Closures cannot mutate immutable captured variables.
2151
2152 Erroneous code example:
2153
2154 ```compile_fail,E0594
2155 let x = 3; // error: closure cannot assign to immutable local variable `x`
2156 let mut c = || { x += 1 };
2157 ```
2158
2159 Make the variable binding mutable:
2160
2161 ```
2162 let mut x = 3; // ok!
2163 let mut c = || { x += 1 };
2164 ```
2165 "##,
2166
2167 E0596: r##"
2168 This error occurs because you tried to mutably borrow a non-mutable variable.
2169
2170 Erroneous code example:
2171
2172 ```compile_fail,E0596
2173 let x = 1;
2174 let y = &mut x; // error: cannot borrow mutably
2175 ```
2176
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:
2179
2180 ```
2181 let mut x = 1;
2182 let y = &mut x; // ok!
2183 ```
2184 "##,
2185
2186 E0597: r##"
2187 This error occurs because a value was dropped while it was still borrowed
2188
2189 Erroneous code example:
2190
2191 ```compile_fail,E0597
2192 struct Foo<'a> {
2193     x: Option<&'a u32>,
2194 }
2195
2196 let mut x = Foo { x: None };
2197 {
2198     let y = 0;
2199     x.x = Some(&y); // error: `y` does not live long enough
2200 }
2201 println!("{:?}", x.x);
2202 ```
2203
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
2207
2208 ```
2209 struct Foo<'a> {
2210     x: Option<&'a u32>,
2211 }
2212
2213 let mut x = Foo { x: None };
2214
2215 let y = 0;
2216 x.x = Some(&y);
2217
2218 println!("{:?}", x.x);
2219 ```
2220 "##,
2221
2222 E0626: r##"
2223 This error occurs because a borrow in a generator persists across a
2224 yield point.
2225
2226 Erroneous code example:
2227
2228 ```compile_fail,E0626
2229 # #![feature(generators, generator_trait, pin)]
2230 # use std::ops::Generator;
2231 # use std::pin::Pin;
2232 let mut b = || {
2233     let a = &String::new(); // <-- This borrow...
2234     yield (); // ...is still in scope here, when the yield occurs.
2235     println!("{}", a);
2236 };
2237 Pin::new(&mut b).resume();
2238 ```
2239
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:
2246
2247 ```
2248 # #![feature(generators, generator_trait, pin)]
2249 # use std::ops::Generator;
2250 # use std::pin::Pin;
2251 let mut b = || {
2252     let a = 3;
2253     yield ();
2254     println!("{}", a);
2255 };
2256 Pin::new(&mut b).resume();
2257 ```
2258
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.
2262
2263 This error also frequently arises with iteration:
2264
2265 ```compile_fail,E0626
2266 # #![feature(generators, generator_trait, pin)]
2267 # use std::ops::Generator;
2268 # use std::pin::Pin;
2269 let mut b = || {
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.
2273   }
2274 };
2275 Pin::new(&mut b).resume();
2276 ```
2277
2278 Such cases can sometimes be resolved by iterating "by value" (or using
2279 `into_iter()`) to avoid borrowing:
2280
2281 ```
2282 # #![feature(generators, generator_trait, pin)]
2283 # use std::ops::Generator;
2284 # use std::pin::Pin;
2285 let mut b = || {
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.
2289   }
2290 };
2291 Pin::new(&mut b).resume();
2292 ```
2293
2294 If taking ownership is not an option, using indices can work too:
2295
2296 ```
2297 # #![feature(generators, generator_trait, pin)]
2298 # use std::ops::Generator;
2299 # use std::pin::Pin;
2300 let mut b = || {
2301   let v = vec![1,2,3];
2302   let len = v.len(); // (*)
2303   for i in 0..len {
2304     let x = v[i]; // (*)
2305     yield x; // <-- Now yield is OK.
2306   }
2307 };
2308 Pin::new(&mut b).resume();
2309
2310 // (*) -- Unfortunately, these temporaries are currently required.
2311 // See <https://github.com/rust-lang/rust/issues/43122>.
2312 ```
2313 "##,
2314
2315 E0712: r##"
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.
2318
2319 Erroneous code example:
2320
2321 ```compile_fail,E0712
2322 #![feature(thread_local)]
2323
2324 #[thread_local]
2325 static FOO: u8 = 3;
2326
2327 fn main() {
2328     let a = &FOO; // error: thread-local variable borrowed past end of function
2329
2330     std::thread::spawn(move || {
2331         println!("{}", a);
2332     });
2333 }
2334 ```
2335 "##,
2336
2337 E0713: r##"
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.
2340
2341 Erroneous code example:
2342
2343 ```compile_fail,E0713
2344 #![feature(nll)]
2345
2346 pub struct S<'a> { data: &'a mut String }
2347
2348 impl<'a> Drop for S<'a> {
2349     fn drop(&mut self) { self.data.push_str("being dropped"); }
2350 }
2351
2352 fn demo<'a>(s: S<'a>) -> &'a mut String { let p = &mut *s.data; p }
2353 ```
2354
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`.
2358
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.
2362
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.
2368
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`
2371 by reference:
2372
2373 ```
2374 pub struct S<'a> { data: &'a mut String }
2375
2376 impl<'a> Drop for S<'a> {
2377     fn drop(&mut self) { self.data.push_str("being dropped"); }
2378 }
2379
2380 fn demo<'a>(s: &'a mut S<'a>) -> &'a mut String { let p = &mut *(*s).data; p }
2381 ```
2382
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
2388 access.
2389 "##,
2390
2391 E0716: r##"
2392 This error indicates that a temporary value is being dropped
2393 while a borrow is still in active use.
2394
2395 Erroneous code example:
2396
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
2402 let q = *p;
2403 ```
2404
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
2410 to this:
2411
2412 ```compile_fail,E0597
2413 # fn foo() -> i32 { 22 }
2414 # fn bar(x: &i32) -> &i32 { x }
2415 let p = {
2416   let tmp = foo(); // the temporary
2417   bar(&tmp)
2418 }; // <-- tmp is freed as we exit this block
2419 let q = p;
2420 ```
2421
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.
2427
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
2431 the following:
2432
2433 ```
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);
2438 let q = *p;
2439 ```
2440
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.
2445
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()`:
2452
2453 ```
2454 fn foo() -> i32 { 22 }
2455 fn bar(x: &i32) -> &i32 { x }
2456 let value = &foo();
2457 let p = bar(value);
2458 let q = *p;
2459 ```
2460
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:
2465
2466 ```
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
2470 // enclosing block.
2471 fn foo() -> i32 { 22 }
2472 let value = (&foo(), &foo());
2473 ```
2474 "##,
2475
2476 E0723: r##"
2477 An feature unstable in `const` contexts was used.
2478
2479 Erroneous code example:
2480
2481 ```compile_fail,E0723
2482 trait T {}
2483
2484 impl T for () {}
2485
2486 const fn foo() -> impl T { // error: `impl Trait` in const fn is unstable
2487     ()
2488 }
2489 ```
2490
2491 To enable this feature on a nightly version of rustc, add the `const_fn`
2492 feature flag:
2493
2494 ```
2495 #![feature(const_fn)]
2496
2497 trait T {}
2498
2499 impl T for () {}
2500
2501 const fn foo() -> impl T {
2502     ()
2503 }
2504 ```
2505 "##,
2506
2507 E0729: r##"
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.
2512
2513 ### What do I do?
2514
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.
2519
2520 ### Shouldn't you fix the old borrow checker?
2521
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.
2524
2525 ### Can I turn these warnings into errors by denying a lint?
2526
2527 No.
2528
2529 ### When are these warnings going to turn into errors?
2530
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
2533 information.
2534
2535 ### Why do I get this message with code that doesn't involve borrowing?
2536
2537 There are some known bugs that trigger this message.
2538 "##,
2539
2540 ;
2541
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
2552 }