]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/error_codes.rs
Uncomment E0386 to let users have access to its old definition
[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. Erroneous code example:
68
69 ```compile_fail,E0004
70 enum Terminator {
71     HastaLaVistaBaby,
72     TalkToMyHand,
73 }
74
75 let x = Terminator::HastaLaVistaBaby;
76
77 match x { // error: non-exhaustive patterns: `HastaLaVistaBaby` not covered
78     Terminator::TalkToMyHand => {}
79 }
80 ```
81
82 If you encounter this error you must alter your patterns so that every possible
83 value of the input type is matched. For types with a small number of variants
84 (like enums) you should probably cover all cases explicitly. Alternatively, the
85 underscore `_` wildcard pattern can be added after all other patterns to match
86 "anything else". Example:
87
88 ```
89 enum Terminator {
90     HastaLaVistaBaby,
91     TalkToMyHand,
92 }
93
94 let x = Terminator::HastaLaVistaBaby;
95
96 match x {
97     Terminator::TalkToMyHand => {}
98     Terminator::HastaLaVistaBaby => {}
99 }
100
101 // or:
102
103 match x {
104     Terminator::TalkToMyHand => {}
105     _ => {}
106 }
107 ```
108 "##,
109
110 E0005: r##"
111 Patterns used to bind names must be irrefutable, that is, they must guarantee
112 that a name will be extracted in all cases. Erroneous code example:
113
114 ```compile_fail,E0005
115 let x = Some(1);
116 let Some(y) = x;
117 // error: refutable pattern in local binding: `None` not covered
118 ```
119
120 If you encounter this error you probably need to use a `match` or `if let` to
121 deal with the possibility of failure. Example:
122
123 ```
124 let x = Some(1);
125
126 match x {
127     Some(y) => {
128         // do something
129     },
130     None => {}
131 }
132
133 // or:
134
135 if let Some(y) = x {
136     // do something
137 }
138 ```
139 "##,
140
141 E0007: r##"
142 This error indicates that the bindings in a match arm would require a value to
143 be moved into more than one location, thus violating unique ownership. Code
144 like the following is invalid as it requires the entire `Option<String>` to be
145 moved into a variable called `op_string` while simultaneously requiring the
146 inner `String` to be moved into a variable called `s`.
147
148 ```compile_fail,E0007
149 let x = Some("s".to_string());
150
151 match x {
152     op_string @ Some(s) => {}, // error: cannot bind by-move with sub-bindings
153     None => {},
154 }
155 ```
156
157 See also the error E0303.
158 "##,
159
160 E0009: r##"
161 In a pattern, all values that don't implement the `Copy` trait have to be bound
162 the same way. The goal here is to avoid binding simultaneously by-move and
163 by-ref.
164
165 This limitation may be removed in a future version of Rust.
166
167 Erroneous code example:
168
169 ```compile_fail,E0009
170 struct X { x: (), }
171
172 let x = Some((X { x: () }, X { x: () }));
173 match x {
174     Some((y, ref z)) => {}, // error: cannot bind by-move and by-ref in the
175                             //        same pattern
176     None => panic!()
177 }
178 ```
179
180 You have two solutions:
181
182 Solution #1: Bind the pattern's values the same way.
183
184 ```
185 struct X { x: (), }
186
187 let x = Some((X { x: () }, X { x: () }));
188 match x {
189     Some((ref y, ref z)) => {},
190     // or Some((y, z)) => {}
191     None => panic!()
192 }
193 ```
194
195 Solution #2: Implement the `Copy` trait for the `X` structure.
196
197 However, please keep in mind that the first solution should be preferred.
198
199 ```
200 #[derive(Clone, Copy)]
201 struct X { x: (), }
202
203 let x = Some((X { x: () }, X { x: () }));
204 match x {
205     Some((y, ref z)) => {},
206     None => panic!()
207 }
208 ```
209 "##,
210
211 E0010: r##"
212 The value of statics and constants must be known at compile time, and they live
213 for the entire lifetime of a program. Creating a boxed value allocates memory on
214 the heap at runtime, and therefore cannot be done at compile time. Erroneous
215 code example:
216
217 ```compile_fail,E0010
218 #![feature(box_syntax)]
219
220 const CON : Box<i32> = box 0;
221 ```
222 "##,
223
224 E0013: r##"
225 Static and const variables can refer to other const variables. But a const
226 variable cannot refer to a static variable. For example, `Y` cannot refer to
227 `X` here:
228
229 ```compile_fail,E0013
230 static X: i32 = 42;
231 const Y: i32 = X;
232 ```
233
234 To fix this, the value can be extracted as a const and then used:
235
236 ```
237 const A: i32 = 42;
238 static X: i32 = A;
239 const Y: i32 = A;
240 ```
241 "##,
242
243 // FIXME(#57563) Change the language here when const fn stabilizes
244 E0015: r##"
245 The only functions that can be called in static or constant expressions are
246 `const` functions, and struct/enum constructors. `const` functions are only
247 available on a nightly compiler. Rust currently does not support more general
248 compile-time function execution.
249
250 ```
251 const FOO: Option<u8> = Some(1); // enum constructor
252 struct Bar {x: u8}
253 const BAR: Bar = Bar {x: 1}; // struct constructor
254 ```
255
256 See [RFC 911] for more details on the design of `const fn`s.
257
258 [RFC 911]: https://github.com/rust-lang/rfcs/blob/master/text/0911-const-fn.md
259 "##,
260
261 E0017: r##"
262 References in statics and constants may only refer to immutable values.
263 Erroneous code example:
264
265 ```compile_fail,E0017
266 static X: i32 = 1;
267 const C: i32 = 2;
268
269 // these three are not allowed:
270 const CR: &mut i32 = &mut C;
271 static STATIC_REF: &'static mut i32 = &mut X;
272 static CONST_REF: &'static mut i32 = &mut C;
273 ```
274
275 Statics are shared everywhere, and if they refer to mutable data one might
276 violate memory safety since holding multiple mutable references to shared data
277 is not allowed.
278
279 If you really want global mutable state, try using `static mut` or a global
280 `UnsafeCell`.
281 "##,
282
283 E0019: r##"
284 A function call isn't allowed in the const's initialization expression
285 because the expression's value must be known at compile-time. Erroneous code
286 example:
287
288 ```compile_fail
289 enum Test {
290     V1
291 }
292
293 impl Test {
294     fn test(&self) -> i32 {
295         12
296     }
297 }
298
299 fn main() {
300     const FOO: Test = Test::V1;
301
302     const A: i32 = FOO.test(); // You can't call Test::func() here!
303 }
304 ```
305
306 Remember: you can't use a function call inside a const's initialization
307 expression! However, you can totally use it anywhere else:
308
309 ```
310 enum Test {
311     V1
312 }
313
314 impl Test {
315     fn func(&self) -> i32 {
316         12
317     }
318 }
319
320 fn main() {
321     const FOO: Test = Test::V1;
322
323     FOO.func(); // here is good
324     let x = FOO.func(); // or even here!
325 }
326 ```
327 "##,
328
329 E0030: r##"
330 When matching against a range, the compiler verifies that the range is
331 non-empty.  Range patterns include both end-points, so this is equivalent to
332 requiring the start of the range to be less than or equal to the end of the
333 range.
334
335 For example:
336
337 ```compile_fail
338 match 5u32 {
339     // This range is ok, albeit pointless.
340     1 ..= 1 => {}
341     // This range is empty, and the compiler can tell.
342     1000 ..= 5 => {}
343 }
344 ```
345 "##,
346
347 E0133: r##"
348 Unsafe code was used outside of an unsafe function or block.
349
350 Erroneous code example:
351
352 ```compile_fail,E0133
353 unsafe fn f() { return; } // This is the unsafe code
354
355 fn main() {
356     f(); // error: call to unsafe function requires unsafe function or block
357 }
358 ```
359
360 Using unsafe functionality is potentially dangerous and disallowed by safety
361 checks. Examples:
362
363 * Dereferencing raw pointers
364 * Calling functions via FFI
365 * Calling functions marked unsafe
366
367 These safety checks can be relaxed for a section of the code by wrapping the
368 unsafe instructions with an `unsafe` block. For instance:
369
370 ```
371 unsafe fn f() { return; }
372
373 fn main() {
374     unsafe { f(); } // ok!
375 }
376 ```
377
378 See also https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html
379 "##,
380
381 E0158: r##"
382 `const` and `static` mean different things. A `const` is a compile-time
383 constant, an alias for a literal value. This property means you can match it
384 directly within a pattern.
385
386 The `static` keyword, on the other hand, guarantees a fixed location in memory.
387 This does not always mean that the value is constant. For example, a global
388 mutex can be declared `static` as well.
389
390 If you want to match against a `static`, consider using a guard instead:
391
392 ```
393 static FORTY_TWO: i32 = 42;
394
395 match Some(42) {
396     Some(x) if x == FORTY_TWO => {}
397     _ => {}
398 }
399 ```
400 "##,
401
402 E0161: r##"
403 A value was moved. However, its size was not known at compile time, and only
404 values of a known size can be moved.
405
406 Erroneous code example:
407
408 ```compile_fail
409 #![feature(box_syntax)]
410
411 fn main() {
412     let array: &[isize] = &[1, 2, 3];
413     let _x: Box<[isize]> = box *array;
414     // error: cannot move a value of type [isize]: the size of [isize] cannot
415     //        be statically determined
416 }
417 ```
418
419 In Rust, you can only move a value when its size is known at compile time.
420
421 To work around this restriction, consider "hiding" the value behind a reference:
422 either `&x` or `&mut x`. Since a reference has a fixed size, this lets you move
423 it around as usual. Example:
424
425 ```
426 #![feature(box_syntax)]
427
428 fn main() {
429     let array: &[isize] = &[1, 2, 3];
430     let _x: Box<&[isize]> = box array; // ok!
431 }
432 ```
433 "##,
434
435 E0162: r##"
436 #### Note: this error code is no longer emitted by the compiler.
437
438 An if-let pattern attempts to match the pattern, and enters the body if the
439 match was successful. If the match is irrefutable (when it cannot fail to
440 match), use a regular `let`-binding instead. For instance:
441
442 ```
443 struct Irrefutable(i32);
444 let irr = Irrefutable(0);
445
446 // This fails to compile because the match is irrefutable.
447 if let Irrefutable(x) = irr {
448     // This body will always be executed.
449     // ...
450 }
451 ```
452
453 Try this instead:
454
455 ```
456 struct Irrefutable(i32);
457 let irr = Irrefutable(0);
458
459 let Irrefutable(x) = irr;
460 println!("{}", x);
461 ```
462 "##,
463
464 E0165: r##"
465 #### Note: this error code is no longer emitted by the compiler.
466
467 A while-let pattern attempts to match the pattern, and enters the body if the
468 match was successful. If the match is irrefutable (when it cannot fail to
469 match), use a regular `let`-binding inside a `loop` instead. For instance:
470
471 ```no_run
472 struct Irrefutable(i32);
473 let irr = Irrefutable(0);
474
475 // This fails to compile because the match is irrefutable.
476 while let Irrefutable(x) = irr {
477     // ...
478 }
479 ```
480
481 Try this instead:
482
483 ```no_run
484 struct Irrefutable(i32);
485 let irr = Irrefutable(0);
486
487 loop {
488     let Irrefutable(x) = irr;
489     // ...
490 }
491 ```
492 "##,
493
494 E0170: r##"
495 Enum variants are qualified by default. For example, given this type:
496
497 ```
498 enum Method {
499     GET,
500     POST,
501 }
502 ```
503
504 You would match it using:
505
506 ```
507 enum Method {
508     GET,
509     POST,
510 }
511
512 let m = Method::GET;
513
514 match m {
515     Method::GET => {},
516     Method::POST => {},
517 }
518 ```
519
520 If you don't qualify the names, the code will bind new variables named "GET" and
521 "POST" instead. This behavior is likely not what you want, so `rustc` warns when
522 that happens.
523
524 Qualified names are good practice, and most code works well with them. But if
525 you prefer them unqualified, you can import the variants into scope:
526
527 ```
528 use Method::*;
529 enum Method { GET, POST }
530 # fn main() {}
531 ```
532
533 If you want others to be able to import variants from your module directly, use
534 `pub use`:
535
536 ```
537 pub use Method::*;
538 pub enum Method { GET, POST }
539 # fn main() {}
540 ```
541 "##,
542
543
544 E0297: r##"
545 #### Note: this error code is no longer emitted by the compiler.
546
547 Patterns used to bind names must be irrefutable. That is, they must guarantee
548 that a name will be extracted in all cases. Instead of pattern matching the
549 loop variable, consider using a `match` or `if let` inside the loop body. For
550 instance:
551
552 ```compile_fail,E0005
553 let xs : Vec<Option<i32>> = vec![Some(1), None];
554
555 // This fails because `None` is not covered.
556 for Some(x) in xs {
557     // ...
558 }
559 ```
560
561 Match inside the loop instead:
562
563 ```
564 let xs : Vec<Option<i32>> = vec![Some(1), None];
565
566 for item in xs {
567     match item {
568         Some(x) => {},
569         None => {},
570     }
571 }
572 ```
573
574 Or use `if let`:
575
576 ```
577 let xs : Vec<Option<i32>> = vec![Some(1), None];
578
579 for item in xs {
580     if let Some(x) = item {
581         // ...
582     }
583 }
584 ```
585 "##,
586
587 E0301: r##"
588 #### Note: this error code is no longer emitted by the compiler.
589
590 Mutable borrows are not allowed in pattern guards, because matching cannot have
591 side effects. Side effects could alter the matched object or the environment
592 on which the match depends in such a way, that the match would not be
593 exhaustive. For instance, the following would not match any arm if mutable
594 borrows were allowed:
595
596 ```compile_fail,E0596
597 match Some(()) {
598     None => { },
599     option if option.take().is_none() => {
600         /* impossible, option is `Some` */
601     },
602     Some(_) => { } // When the previous match failed, the option became `None`.
603 }
604 ```
605 "##,
606
607 E0302: r##"
608 #### Note: this error code is no longer emitted by the compiler.
609
610 Assignments are not allowed in pattern guards, because matching cannot have
611 side effects. Side effects could alter the matched object or the environment
612 on which the match depends in such a way, that the match would not be
613 exhaustive. For instance, the following would not match any arm if assignments
614 were allowed:
615
616 ```compile_fail,E0594
617 match Some(()) {
618     None => { },
619     option if { option = None; false } => { },
620     Some(_) => { } // When the previous match failed, the option became `None`.
621 }
622 ```
623 "##,
624
625 E0303: r##"
626 In certain cases it is possible for sub-bindings to violate memory safety.
627 Updates to the borrow checker in a future version of Rust may remove this
628 restriction, but for now patterns must be rewritten without sub-bindings.
629
630 Before:
631
632 ```compile_fail,E0303
633 match Some("hi".to_string()) {
634     ref op_string_ref @ Some(s) => {},
635     None => {},
636 }
637 ```
638
639 After:
640
641 ```
642 match Some("hi".to_string()) {
643     Some(ref s) => {
644         let op_string_ref = &Some(s);
645         // ...
646     },
647     None => {},
648 }
649 ```
650
651 The `op_string_ref` binding has type `&Option<&String>` in both cases.
652
653 See also https://github.com/rust-lang/rust/issues/14587
654 "##,
655
656 E0373: r##"
657 This error occurs when an attempt is made to use data captured by a closure,
658 when that data may no longer exist. It's most commonly seen when attempting to
659 return a closure:
660
661 ```compile_fail,E0373
662 fn foo() -> Box<Fn(u32) -> u32> {
663     let x = 0u32;
664     Box::new(|y| x + y)
665 }
666 ```
667
668 Notice that `x` is stack-allocated by `foo()`. By default, Rust captures
669 closed-over data by reference. This means that once `foo()` returns, `x` no
670 longer exists. An attempt to access `x` within the closure would thus be
671 unsafe.
672
673 Another situation where this might be encountered is when spawning threads:
674
675 ```compile_fail,E0373
676 fn foo() {
677     let x = 0u32;
678     let y = 1u32;
679
680     let thr = std::thread::spawn(|| {
681         x + y
682     });
683 }
684 ```
685
686 Since our new thread runs in parallel, the stack frame containing `x` and `y`
687 may well have disappeared by the time we try to use them. Even if we call
688 `thr.join()` within foo (which blocks until `thr` has completed, ensuring the
689 stack frame won't disappear), we will not succeed: the compiler cannot prove
690 that this behaviour is safe, and so won't let us do it.
691
692 The solution to this problem is usually to switch to using a `move` closure.
693 This approach moves (or copies, where possible) data into the closure, rather
694 than taking references to it. For example:
695
696 ```
697 fn foo() -> Box<Fn(u32) -> u32> {
698     let x = 0u32;
699     Box::new(move |y| x + y)
700 }
701 ```
702
703 Now that the closure has its own copy of the data, there's no need to worry
704 about safety.
705 "##,
706
707 E0381: r##"
708 It is not allowed to use or capture an uninitialized variable. For example:
709
710 ```compile_fail,E0381
711 fn main() {
712     let x: i32;
713     let y = x; // error, use of possibly-uninitialized variable
714 }
715 ```
716
717 To fix this, ensure that any declared variables are initialized before being
718 used. Example:
719
720 ```
721 fn main() {
722     let x: i32 = 0;
723     let y = x; // ok!
724 }
725 ```
726 "##,
727
728 E0382: r##"
729 This error occurs when an attempt is made to use a variable after its contents
730 have been moved elsewhere. For example:
731
732 ```compile_fail,E0382
733 struct MyStruct { s: u32 }
734
735 fn main() {
736     let mut x = MyStruct{ s: 5u32 };
737     let y = x;
738     x.s = 6;
739     println!("{}", x.s);
740 }
741 ```
742
743 Since `MyStruct` is a type that is not marked `Copy`, the data gets moved out
744 of `x` when we set `y`. This is fundamental to Rust's ownership system: outside
745 of workarounds like `Rc`, a value cannot be owned by more than one variable.
746
747 Sometimes we don't need to move the value. Using a reference, we can let another
748 function borrow the value without changing its ownership. In the example below,
749 we don't actually have to move our string to `calculate_length`, we can give it
750 a reference to it with `&` instead.
751
752 ```
753 fn main() {
754     let s1 = String::from("hello");
755
756     let len = calculate_length(&s1);
757
758     println!("The length of '{}' is {}.", s1, len);
759 }
760
761 fn calculate_length(s: &String) -> usize {
762     s.len()
763 }
764 ```
765
766 A mutable reference can be created with `&mut`.
767
768 Sometimes we don't want a reference, but a duplicate. All types marked `Clone`
769 can be duplicated by calling `.clone()`. Subsequent changes to a clone do not
770 affect the original variable.
771
772 Most types in the standard library are marked `Clone`. The example below
773 demonstrates using `clone()` on a string. `s1` is first set to "many", and then
774 copied to `s2`. Then the first character of `s1` is removed, without affecting
775 `s2`. "any many" is printed to the console.
776
777 ```
778 fn main() {
779     let mut s1 = String::from("many");
780     let s2 = s1.clone();
781     s1.remove(0);
782     println!("{} {}", s1, s2);
783 }
784 ```
785
786 If we control the definition of a type, we can implement `Clone` on it ourselves
787 with `#[derive(Clone)]`.
788
789 Some types have no ownership semantics at all and are trivial to duplicate. An
790 example is `i32` and the other number types. We don't have to call `.clone()` to
791 clone them, because they are marked `Copy` in addition to `Clone`.  Implicit
792 cloning is more convenient in this case. We can mark our own types `Copy` if
793 all their members also are marked `Copy`.
794
795 In the example below, we implement a `Point` type. Because it only stores two
796 integers, we opt-out of ownership semantics with `Copy`. Then we can
797 `let p2 = p1` without `p1` being moved.
798
799 ```
800 #[derive(Copy, Clone)]
801 struct Point { x: i32, y: i32 }
802
803 fn main() {
804     let mut p1 = Point{ x: -1, y: 2 };
805     let p2 = p1;
806     p1.x = 1;
807     println!("p1: {}, {}", p1.x, p1.y);
808     println!("p2: {}, {}", p2.x, p2.y);
809 }
810 ```
811
812 Alternatively, if we don't control the struct's definition, or mutable shared
813 ownership is truly required, we can use `Rc` and `RefCell`:
814
815 ```
816 use std::cell::RefCell;
817 use std::rc::Rc;
818
819 struct MyStruct { s: u32 }
820
821 fn main() {
822     let mut x = Rc::new(RefCell::new(MyStruct{ s: 5u32 }));
823     let y = x.clone();
824     x.borrow_mut().s = 6;
825     println!("{}", x.borrow().s);
826 }
827 ```
828
829 With this approach, x and y share ownership of the data via the `Rc` (reference
830 count type). `RefCell` essentially performs runtime borrow checking: ensuring
831 that at most one writer or multiple readers can access the data at any one time.
832
833 If you wish to learn more about ownership in Rust, start with the chapter in the
834 Book:
835
836 https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html
837 "##,
838
839 E0383: r##"
840 #### Note: this error code is no longer emitted by the compiler.
841
842 This error occurs when an attempt is made to partially reinitialize a
843 structure that is currently uninitialized.
844
845 For example, this can happen when a drop has taken place:
846
847 ```compile_fail
848 struct Foo {
849     a: u32,
850 }
851 impl Drop for Foo {
852     fn drop(&mut self) { /* ... */ }
853 }
854
855 let mut x = Foo { a: 1 };
856 drop(x); // `x` is now uninitialized
857 x.a = 2; // error, partial reinitialization of uninitialized structure `t`
858 ```
859
860 This error can be fixed by fully reinitializing the structure in question:
861
862 ```
863 struct Foo {
864     a: u32,
865 }
866 impl Drop for Foo {
867     fn drop(&mut self) { /* ... */ }
868 }
869
870 let mut x = Foo { a: 1 };
871 drop(x);
872 x = Foo { a: 2 };
873 ```
874 "##,
875
876 E0384: r##"
877 This error occurs when an attempt is made to reassign an immutable variable.
878
879 Erroneous code example:
880
881 ```compile_fail,E0384
882 fn main() {
883     let x = 3;
884     x = 5; // error, reassignment of immutable variable
885 }
886 ```
887
888 By default, variables in Rust are immutable. To fix this error, add the keyword
889 `mut` after the keyword `let` when declaring the variable. For example:
890
891 ```
892 fn main() {
893     let mut x = 3;
894     x = 5;
895 }
896 ```
897 "##,
898
899 E0386: r##"
900 #### Note: this error code is no longer emitted by the compiler.
901
902 This error occurs when an attempt is made to mutate the target of a mutable
903 reference stored inside an immutable container.
904
905 For example, this can happen when storing a `&mut` inside an immutable `Box`:
906
907 ```
908 let mut x: i64 = 1;
909 let y: Box<_> = Box::new(&mut x);
910 **y = 2; // error, cannot assign to data in an immutable container
911 ```
912
913 This error can be fixed by making the container mutable:
914
915 ```
916 let mut x: i64 = 1;
917 let mut y: Box<_> = Box::new(&mut x);
918 **y = 2;
919 ```
920
921 It can also be fixed by using a type with interior mutability, such as `Cell`
922 or `RefCell`:
923
924 ```
925 use std::cell::Cell;
926
927 let x: i64 = 1;
928 let y: Box<Cell<_>> = Box::new(Cell::new(x));
929 y.set(2);
930 ```
931 "##,
932
933 E0387: r##"
934 #### Note: this error code is no longer emitted by the compiler.
935
936 This error occurs when an attempt is made to mutate or mutably reference data
937 that a closure has captured immutably. Examples of this error are shown below:
938
939 ```compile_fail
940 // Accepts a function or a closure that captures its environment immutably.
941 // Closures passed to foo will not be able to mutate their closed-over state.
942 fn foo<F: Fn()>(f: F) { }
943
944 // Attempts to mutate closed-over data. Error message reads:
945 // `cannot assign to data in a captured outer variable...`
946 fn mutable() {
947     let mut x = 0u32;
948     foo(|| x = 2);
949 }
950
951 // Attempts to take a mutable reference to closed-over data.  Error message
952 // reads: `cannot borrow data mutably in a captured outer variable...`
953 fn mut_addr() {
954     let mut x = 0u32;
955     foo(|| { let y = &mut x; });
956 }
957 ```
958
959 The problem here is that foo is defined as accepting a parameter of type `Fn`.
960 Closures passed into foo will thus be inferred to be of type `Fn`, meaning that
961 they capture their context immutably.
962
963 If the definition of `foo` is under your control, the simplest solution is to
964 capture the data mutably. This can be done by defining `foo` to take FnMut
965 rather than Fn:
966
967 ```
968 fn foo<F: FnMut()>(f: F) { }
969 ```
970
971 Alternatively, we can consider using the `Cell` and `RefCell` types to achieve
972 interior mutability through a shared reference. Our example's `mutable`
973 function could be redefined as below:
974
975 ```
976 use std::cell::Cell;
977
978 fn foo<F: Fn()>(f: F) { }
979
980 fn mutable() {
981     let x = Cell::new(0u32);
982     foo(|| x.set(2));
983 }
984 ```
985
986 You can read more about cell types in the API documentation:
987
988 https://doc.rust-lang.org/std/cell/
989 "##,
990
991 E0388: r##"
992 #### Note: this error code is no longer emitted by the compiler.
993 "##,
994
995 E0389: r##"
996 #### Note: this error code is no longer emitted by the compiler.
997
998 An attempt was made to mutate data using a non-mutable reference. This
999 commonly occurs when attempting to assign to a non-mutable reference of a
1000 mutable reference (`&(&mut T)`).
1001
1002 Example of erroneous code:
1003
1004 ```compile_fail
1005 struct FancyNum {
1006     num: u8,
1007 }
1008
1009 fn main() {
1010     let mut fancy = FancyNum{ num: 5 };
1011     let fancy_ref = &(&mut fancy);
1012     fancy_ref.num = 6; // error: cannot assign to data in a `&` reference
1013     println!("{}", fancy_ref.num);
1014 }
1015 ```
1016
1017 Here, `&mut fancy` is mutable, but `&(&mut fancy)` is not. Creating an
1018 immutable reference to a value borrows it immutably. There can be multiple
1019 references of type `&(&mut T)` that point to the same value, so they must be
1020 immutable to prevent multiple mutable references to the same value.
1021
1022 To fix this, either remove the outer reference:
1023
1024 ```
1025 struct FancyNum {
1026     num: u8,
1027 }
1028
1029 fn main() {
1030     let mut fancy = FancyNum{ num: 5 };
1031
1032     let fancy_ref = &mut fancy;
1033     // `fancy_ref` is now &mut FancyNum, rather than &(&mut FancyNum)
1034
1035     fancy_ref.num = 6; // No error!
1036
1037     println!("{}", fancy_ref.num);
1038 }
1039 ```
1040
1041 Or make the outer reference mutable:
1042
1043 ```
1044 struct FancyNum {
1045     num: u8
1046 }
1047
1048 fn main() {
1049     let mut fancy = FancyNum{ num: 5 };
1050
1051     let fancy_ref = &mut (&mut fancy);
1052     // `fancy_ref` is now &mut(&mut FancyNum), rather than &(&mut FancyNum)
1053
1054     fancy_ref.num = 6; // No error!
1055
1056     println!("{}", fancy_ref.num);
1057 }
1058 ```
1059 "##,
1060
1061 E0492: r##"
1062 A borrow of a constant containing interior mutability was attempted. Erroneous
1063 code example:
1064
1065 ```compile_fail,E0492
1066 use std::sync::atomic::AtomicUsize;
1067
1068 const A: AtomicUsize = AtomicUsize::new(0);
1069 static B: &'static AtomicUsize = &A;
1070 // error: cannot borrow a constant which may contain interior mutability,
1071 //        create a static instead
1072 ```
1073
1074 A `const` represents a constant value that should never change. If one takes
1075 a `&` reference to the constant, then one is taking a pointer to some memory
1076 location containing the value. Normally this is perfectly fine: most values
1077 can't be changed via a shared `&` pointer, but interior mutability would allow
1078 it. That is, a constant value could be mutated. On the other hand, a `static` is
1079 explicitly a single memory location, which can be mutated at will.
1080
1081 So, in order to solve this error, either use statics which are `Sync`:
1082
1083 ```
1084 use std::sync::atomic::AtomicUsize;
1085
1086 static A: AtomicUsize = AtomicUsize::new(0);
1087 static B: &'static AtomicUsize = &A; // ok!
1088 ```
1089
1090 You can also have this error while using a cell type:
1091
1092 ```compile_fail,E0492
1093 use std::cell::Cell;
1094
1095 const A: Cell<usize> = Cell::new(1);
1096 const B: &Cell<usize> = &A;
1097 // error: cannot borrow a constant which may contain interior mutability,
1098 //        create a static instead
1099
1100 // or:
1101 struct C { a: Cell<usize> }
1102
1103 const D: C = C { a: Cell::new(1) };
1104 const E: &Cell<usize> = &D.a; // error
1105
1106 // or:
1107 const F: &C = &D; // error
1108 ```
1109
1110 This is because cell types do operations that are not thread-safe. Due to this,
1111 they don't implement Sync and thus can't be placed in statics.
1112
1113 However, if you still wish to use these types, you can achieve this by an unsafe
1114 wrapper:
1115
1116 ```
1117 use std::cell::Cell;
1118 use std::marker::Sync;
1119
1120 struct NotThreadSafe<T> {
1121     value: Cell<T>,
1122 }
1123
1124 unsafe impl<T> Sync for NotThreadSafe<T> {}
1125
1126 static A: NotThreadSafe<usize> = NotThreadSafe { value : Cell::new(1) };
1127 static B: &'static NotThreadSafe<usize> = &A; // ok!
1128 ```
1129
1130 Remember this solution is unsafe! You will have to ensure that accesses to the
1131 cell are synchronized.
1132 "##,
1133
1134 E0493: r##"
1135 A type with a `Drop` implementation was destructured when trying to initialize
1136 a static item.
1137
1138 Erroneous code example:
1139
1140 ```compile_fail,E0493
1141 enum DropType {
1142     A,
1143 }
1144
1145 impl Drop for DropType {
1146     fn drop(&mut self) {}
1147 }
1148
1149 struct Foo {
1150     field1: DropType,
1151 }
1152
1153 static FOO: Foo = Foo { ..Foo { field1: DropType::A } }; // error!
1154 ```
1155
1156 The problem here is that if the given type or one of its fields implements the
1157 `Drop` trait, this `Drop` implementation cannot be called during the static
1158 type initialization which might cause a memory leak. To prevent this issue,
1159 you need to instantiate all the static type's fields by hand.
1160
1161 ```
1162 enum DropType {
1163     A,
1164 }
1165
1166 impl Drop for DropType {
1167     fn drop(&mut self) {}
1168 }
1169
1170 struct Foo {
1171     field1: DropType,
1172 }
1173
1174 static FOO: Foo = Foo { field1: DropType::A }; // We initialize all fields
1175                                                // by hand.
1176 ```
1177 "##,
1178
1179 E0499: r##"
1180 A variable was borrowed as mutable more than once. Erroneous code example:
1181
1182 ```compile_fail,E0499
1183 let mut i = 0;
1184 let mut x = &mut i;
1185 let mut a = &mut i;
1186 x;
1187 // error: cannot borrow `i` as mutable more than once at a time
1188 ```
1189
1190 Please note that in rust, you can either have many immutable references, or one
1191 mutable reference. Take a look at
1192 https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html for more
1193 information. Example:
1194
1195
1196 ```
1197 let mut i = 0;
1198 let mut x = &mut i; // ok!
1199
1200 // or:
1201 let mut i = 0;
1202 let a = &i; // ok!
1203 let b = &i; // still ok!
1204 let c = &i; // still ok!
1205 b;
1206 a;
1207 ```
1208 "##,
1209
1210 E0500: r##"
1211 A borrowed variable was used by a closure. Example of erroneous code:
1212
1213 ```compile_fail,E0500
1214 fn you_know_nothing(jon_snow: &mut i32) {
1215     let nights_watch = &jon_snow;
1216     let starks = || {
1217         *jon_snow = 3; // error: closure requires unique access to `jon_snow`
1218                        //        but it is already borrowed
1219     };
1220     println!("{}", nights_watch);
1221 }
1222 ```
1223
1224 In here, `jon_snow` is already borrowed by the `nights_watch` reference, so it
1225 cannot be borrowed by the `starks` closure at the same time. To fix this issue,
1226 you can create the closure after the borrow has ended:
1227
1228 ```
1229 fn you_know_nothing(jon_snow: &mut i32) {
1230     let nights_watch = &jon_snow;
1231     println!("{}", nights_watch);
1232     let starks = || {
1233         *jon_snow = 3;
1234     };
1235 }
1236 ```
1237
1238 Or, if the type implements the `Clone` trait, you can clone it between
1239 closures:
1240
1241 ```
1242 fn you_know_nothing(jon_snow: &mut i32) {
1243     let mut jon_copy = jon_snow.clone();
1244     let starks = || {
1245         *jon_snow = 3;
1246     };
1247     println!("{}", jon_copy);
1248 }
1249 ```
1250 "##,
1251
1252 E0501: r##"
1253 This error indicates that a mutable variable is being used while it is still
1254 captured by a closure. Because the closure has borrowed the variable, it is not
1255 available for use until the closure goes out of scope.
1256
1257 Note that a capture will either move or borrow a variable, but in this
1258 situation, the closure is borrowing the variable. Take a look at
1259 http://rustbyexample.com/fn/closures/capture.html for more information about
1260 capturing.
1261
1262 Example of erroneous code:
1263
1264 ```compile_fail,E0501
1265 fn inside_closure(x: &mut i32) {
1266     // Actions which require unique access
1267 }
1268
1269 fn outside_closure(x: &mut i32) {
1270     // Actions which require unique access
1271 }
1272
1273 fn foo(a: &mut i32) {
1274     let mut bar = || {
1275         inside_closure(a)
1276     };
1277     outside_closure(a); // error: cannot borrow `*a` as mutable because previous
1278                         //        closure requires unique access.
1279     bar();
1280 }
1281 ```
1282
1283 To fix this error, you can finish using the closure before using the captured
1284 variable:
1285
1286 ```
1287 fn inside_closure(x: &mut i32) {}
1288 fn outside_closure(x: &mut i32) {}
1289
1290 fn foo(a: &mut i32) {
1291     let mut bar = || {
1292         inside_closure(a)
1293     };
1294     bar();
1295     // borrow on `a` ends.
1296     outside_closure(a); // ok!
1297 }
1298 ```
1299
1300 Or you can pass the variable as a parameter to the closure:
1301
1302 ```
1303 fn inside_closure(x: &mut i32) {}
1304 fn outside_closure(x: &mut i32) {}
1305
1306 fn foo(a: &mut i32) {
1307     let mut bar = |s: &mut i32| {
1308         inside_closure(s)
1309     };
1310     outside_closure(a);
1311     bar(a);
1312 }
1313 ```
1314
1315 It may be possible to define the closure later:
1316
1317 ```
1318 fn inside_closure(x: &mut i32) {}
1319 fn outside_closure(x: &mut i32) {}
1320
1321 fn foo(a: &mut i32) {
1322     outside_closure(a);
1323     let mut bar = || {
1324         inside_closure(a)
1325     };
1326     bar();
1327 }
1328 ```
1329 "##,
1330
1331 E0502: r##"
1332 This error indicates that you are trying to borrow a variable as mutable when it
1333 has already been borrowed as immutable.
1334
1335 Example of erroneous code:
1336
1337 ```compile_fail,E0502
1338 fn bar(x: &mut i32) {}
1339 fn foo(a: &mut i32) {
1340     let ref y = a; // a is borrowed as immutable.
1341     bar(a); // error: cannot borrow `*a` as mutable because `a` is also borrowed
1342             //        as immutable
1343     println!("{}", y);
1344 }
1345 ```
1346
1347 To fix this error, ensure that you don't have any other references to the
1348 variable before trying to access it mutably:
1349
1350 ```
1351 fn bar(x: &mut i32) {}
1352 fn foo(a: &mut i32) {
1353     bar(a);
1354     let ref y = a; // ok!
1355     println!("{}", y);
1356 }
1357 ```
1358
1359 For more information on the rust ownership system, take a look at
1360 https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html.
1361 "##,
1362
1363 E0503: r##"
1364 A value was used after it was mutably borrowed.
1365
1366 Example of erroneous code:
1367
1368 ```compile_fail,E0503
1369 fn main() {
1370     let mut value = 3;
1371     // Create a mutable borrow of `value`.
1372     let borrow = &mut value;
1373     let _sum = value + 1; // error: cannot use `value` because
1374                           //        it was mutably borrowed
1375     println!("{}", borrow);
1376 }
1377 ```
1378
1379 In this example, `value` is mutably borrowed by `borrow` and cannot be
1380 used to calculate `sum`. This is not possible because this would violate
1381 Rust's mutability rules.
1382
1383 You can fix this error by finishing using the borrow before the next use of
1384 the value:
1385
1386 ```
1387 fn main() {
1388     let mut value = 3;
1389     let borrow = &mut value;
1390     println!("{}", borrow);
1391     // The block has ended and with it the borrow.
1392     // You can now use `value` again.
1393     let _sum = value + 1;
1394 }
1395 ```
1396
1397 Or by cloning `value` before borrowing it:
1398
1399 ```
1400 fn main() {
1401     let mut value = 3;
1402     // We clone `value`, creating a copy.
1403     let value_cloned = value.clone();
1404     // The mutable borrow is a reference to `value` and
1405     // not to `value_cloned`...
1406     let borrow = &mut value;
1407     // ... which means we can still use `value_cloned`,
1408     let _sum = value_cloned + 1;
1409     // even though the borrow only ends here.
1410     println!("{}", borrow);
1411 }
1412 ```
1413
1414 You can find more information about borrowing in the rust-book:
1415 http://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html
1416 "##,
1417
1418 E0504: r##"
1419 #### Note: this error code is no longer emitted by the compiler.
1420
1421 This error occurs when an attempt is made to move a borrowed variable into a
1422 closure.
1423
1424 Example of erroneous code:
1425
1426 ```compile_fail
1427 struct FancyNum {
1428     num: u8,
1429 }
1430
1431 fn main() {
1432     let fancy_num = FancyNum { num: 5 };
1433     let fancy_ref = &fancy_num;
1434
1435     let x = move || {
1436         println!("child function: {}", fancy_num.num);
1437         // error: cannot move `fancy_num` into closure because it is borrowed
1438     };
1439
1440     x();
1441     println!("main function: {}", fancy_ref.num);
1442 }
1443 ```
1444
1445 Here, `fancy_num` is borrowed by `fancy_ref` and so cannot be moved into
1446 the closure `x`. There is no way to move a value into a closure while it is
1447 borrowed, as that would invalidate the borrow.
1448
1449 If the closure can't outlive the value being moved, try using a reference
1450 rather than moving:
1451
1452 ```
1453 struct FancyNum {
1454     num: u8,
1455 }
1456
1457 fn main() {
1458     let fancy_num = FancyNum { num: 5 };
1459     let fancy_ref = &fancy_num;
1460
1461     let x = move || {
1462         // fancy_ref is usable here because it doesn't move `fancy_num`
1463         println!("child function: {}", fancy_ref.num);
1464     };
1465
1466     x();
1467
1468     println!("main function: {}", fancy_num.num);
1469 }
1470 ```
1471
1472 If the value has to be borrowed and then moved, try limiting the lifetime of
1473 the borrow using a scoped block:
1474
1475 ```
1476 struct FancyNum {
1477     num: u8,
1478 }
1479
1480 fn main() {
1481     let fancy_num = FancyNum { num: 5 };
1482
1483     {
1484         let fancy_ref = &fancy_num;
1485         println!("main function: {}", fancy_ref.num);
1486         // `fancy_ref` goes out of scope here
1487     }
1488
1489     let x = move || {
1490         // `fancy_num` can be moved now (no more references exist)
1491         println!("child function: {}", fancy_num.num);
1492     };
1493
1494     x();
1495 }
1496 ```
1497
1498 If the lifetime of a reference isn't enough, such as in the case of threading,
1499 consider using an `Arc` to create a reference-counted value:
1500
1501 ```
1502 use std::sync::Arc;
1503 use std::thread;
1504
1505 struct FancyNum {
1506     num: u8,
1507 }
1508
1509 fn main() {
1510     let fancy_ref1 = Arc::new(FancyNum { num: 5 });
1511     let fancy_ref2 = fancy_ref1.clone();
1512
1513     let x = thread::spawn(move || {
1514         // `fancy_ref1` can be moved and has a `'static` lifetime
1515         println!("child thread: {}", fancy_ref1.num);
1516     });
1517
1518     x.join().expect("child thread should finish");
1519     println!("main thread: {}", fancy_ref2.num);
1520 }
1521 ```
1522 "##,
1523
1524 E0505: r##"
1525 A value was moved out while it was still borrowed.
1526
1527 Erroneous code example:
1528
1529 ```compile_fail,E0505
1530 struct Value {}
1531
1532 fn borrow(val: &Value) {}
1533
1534 fn eat(val: Value) {}
1535
1536 fn main() {
1537     let x = Value{};
1538     let _ref_to_val: &Value = &x;
1539     eat(x);
1540     borrow(_ref_to_val);
1541 }
1542 ```
1543
1544 Here, the function `eat` takes ownership of `x`. However,
1545 `x` cannot be moved because the borrow to `_ref_to_val`
1546 needs to last till the function `borrow`.
1547 To fix that you can do a few different things:
1548
1549 * Try to avoid moving the variable.
1550 * Release borrow before move.
1551 * Implement the `Copy` trait on the type.
1552
1553 Examples:
1554
1555 ```
1556 struct Value {}
1557
1558 fn borrow(val: &Value) {}
1559
1560 fn eat(val: &Value) {}
1561
1562 fn main() {
1563     let x = Value{};
1564
1565     let ref_to_val: &Value = &x;
1566     eat(&x); // pass by reference, if it's possible
1567     borrow(ref_to_val);
1568 }
1569 ```
1570
1571 Or:
1572
1573 ```
1574 struct Value {}
1575
1576 fn borrow(val: &Value) {}
1577
1578 fn eat(val: Value) {}
1579
1580 fn main() {
1581     let x = Value{};
1582
1583     let ref_to_val: &Value = &x;
1584     borrow(ref_to_val);
1585     // ref_to_val is no longer used.
1586     eat(x);
1587 }
1588 ```
1589
1590 Or:
1591
1592 ```
1593 #[derive(Clone, Copy)] // implement Copy trait
1594 struct Value {}
1595
1596 fn borrow(val: &Value) {}
1597
1598 fn eat(val: Value) {}
1599
1600 fn main() {
1601     let x = Value{};
1602     let ref_to_val: &Value = &x;
1603     eat(x); // it will be copied here.
1604     borrow(ref_to_val);
1605 }
1606 ```
1607
1608 You can find more information about borrowing in the rust-book:
1609 http://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html
1610 "##,
1611
1612 E0506: r##"
1613 This error occurs when an attempt is made to assign to a borrowed value.
1614
1615 Example of erroneous code:
1616
1617 ```compile_fail,E0506
1618 struct FancyNum {
1619     num: u8,
1620 }
1621
1622 fn main() {
1623     let mut fancy_num = FancyNum { num: 5 };
1624     let fancy_ref = &fancy_num;
1625     fancy_num = FancyNum { num: 6 };
1626     // error: cannot assign to `fancy_num` because it is borrowed
1627
1628     println!("Num: {}, Ref: {}", fancy_num.num, fancy_ref.num);
1629 }
1630 ```
1631
1632 Because `fancy_ref` still holds a reference to `fancy_num`, `fancy_num` can't
1633 be assigned to a new value as it would invalidate the reference.
1634
1635 Alternatively, we can move out of `fancy_num` into a second `fancy_num`:
1636
1637 ```
1638 struct FancyNum {
1639     num: u8,
1640 }
1641
1642 fn main() {
1643     let mut fancy_num = FancyNum { num: 5 };
1644     let moved_num = fancy_num;
1645     fancy_num = FancyNum { num: 6 };
1646
1647     println!("Num: {}, Moved num: {}", fancy_num.num, moved_num.num);
1648 }
1649 ```
1650
1651 If the value has to be borrowed, try limiting the lifetime of the borrow using
1652 a scoped block:
1653
1654 ```
1655 struct FancyNum {
1656     num: u8,
1657 }
1658
1659 fn main() {
1660     let mut fancy_num = FancyNum { num: 5 };
1661
1662     {
1663         let fancy_ref = &fancy_num;
1664         println!("Ref: {}", fancy_ref.num);
1665     }
1666
1667     // Works because `fancy_ref` is no longer in scope
1668     fancy_num = FancyNum { num: 6 };
1669     println!("Num: {}", fancy_num.num);
1670 }
1671 ```
1672
1673 Or by moving the reference into a function:
1674
1675 ```
1676 struct FancyNum {
1677     num: u8,
1678 }
1679
1680 fn main() {
1681     let mut fancy_num = FancyNum { num: 5 };
1682
1683     print_fancy_ref(&fancy_num);
1684
1685     // Works because function borrow has ended
1686     fancy_num = FancyNum { num: 6 };
1687     println!("Num: {}", fancy_num.num);
1688 }
1689
1690 fn print_fancy_ref(fancy_ref: &FancyNum){
1691     println!("Ref: {}", fancy_ref.num);
1692 }
1693 ```
1694 "##,
1695
1696 E0507: r##"
1697 You tried to move out of a value which was borrowed.
1698
1699 This can also happen when using a type implementing `Fn` or `FnMut`, as neither
1700 allows moving out of them (they usually represent closures which can be called
1701 more than once). Much of the text following applies equally well to non-`FnOnce`
1702 closure bodies.
1703
1704 Erroneous code example:
1705
1706 ```compile_fail,E0507
1707 use std::cell::RefCell;
1708
1709 struct TheDarkKnight;
1710
1711 impl TheDarkKnight {
1712     fn nothing_is_true(self) {}
1713 }
1714
1715 fn main() {
1716     let x = RefCell::new(TheDarkKnight);
1717
1718     x.borrow().nothing_is_true(); // error: cannot move out of borrowed content
1719 }
1720 ```
1721
1722 Here, the `nothing_is_true` method takes the ownership of `self`. However,
1723 `self` cannot be moved because `.borrow()` only provides an `&TheDarkKnight`,
1724 which is a borrow of the content owned by the `RefCell`. To fix this error,
1725 you have three choices:
1726
1727 * Try to avoid moving the variable.
1728 * Somehow reclaim the ownership.
1729 * Implement the `Copy` trait on the type.
1730
1731 Examples:
1732
1733 ```
1734 use std::cell::RefCell;
1735
1736 struct TheDarkKnight;
1737
1738 impl TheDarkKnight {
1739     fn nothing_is_true(&self) {} // First case, we don't take ownership
1740 }
1741
1742 fn main() {
1743     let x = RefCell::new(TheDarkKnight);
1744
1745     x.borrow().nothing_is_true(); // ok!
1746 }
1747 ```
1748
1749 Or:
1750
1751 ```
1752 use std::cell::RefCell;
1753
1754 struct TheDarkKnight;
1755
1756 impl TheDarkKnight {
1757     fn nothing_is_true(self) {}
1758 }
1759
1760 fn main() {
1761     let x = RefCell::new(TheDarkKnight);
1762     let x = x.into_inner(); // we get back ownership
1763
1764     x.nothing_is_true(); // ok!
1765 }
1766 ```
1767
1768 Or:
1769
1770 ```
1771 use std::cell::RefCell;
1772
1773 #[derive(Clone, Copy)] // we implement the Copy trait
1774 struct TheDarkKnight;
1775
1776 impl TheDarkKnight {
1777     fn nothing_is_true(self) {}
1778 }
1779
1780 fn main() {
1781     let x = RefCell::new(TheDarkKnight);
1782
1783     x.borrow().nothing_is_true(); // ok!
1784 }
1785 ```
1786
1787 Moving a member out of a mutably borrowed struct will also cause E0507 error:
1788
1789 ```compile_fail,E0507
1790 struct TheDarkKnight;
1791
1792 impl TheDarkKnight {
1793     fn nothing_is_true(self) {}
1794 }
1795
1796 struct Batcave {
1797     knight: TheDarkKnight
1798 }
1799
1800 fn main() {
1801     let mut cave = Batcave {
1802         knight: TheDarkKnight
1803     };
1804     let borrowed = &mut cave;
1805
1806     borrowed.knight.nothing_is_true(); // E0507
1807 }
1808 ```
1809
1810 It is fine only if you put something back. `mem::replace` can be used for that:
1811
1812 ```
1813 # struct TheDarkKnight;
1814 # impl TheDarkKnight { fn nothing_is_true(self) {} }
1815 # struct Batcave { knight: TheDarkKnight }
1816 use std::mem;
1817
1818 let mut cave = Batcave {
1819     knight: TheDarkKnight
1820 };
1821 let borrowed = &mut cave;
1822
1823 mem::replace(&mut borrowed.knight, TheDarkKnight).nothing_is_true(); // ok!
1824 ```
1825
1826 You can find more information about borrowing in the rust-book:
1827 http://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html
1828 "##,
1829
1830 E0508: r##"
1831 A value was moved out of a non-copy fixed-size array.
1832
1833 Example of erroneous code:
1834
1835 ```compile_fail,E0508
1836 struct NonCopy;
1837
1838 fn main() {
1839     let array = [NonCopy; 1];
1840     let _value = array[0]; // error: cannot move out of type `[NonCopy; 1]`,
1841                            //        a non-copy fixed-size array
1842 }
1843 ```
1844
1845 The first element was moved out of the array, but this is not
1846 possible because `NonCopy` does not implement the `Copy` trait.
1847
1848 Consider borrowing the element instead of moving it:
1849
1850 ```
1851 struct NonCopy;
1852
1853 fn main() {
1854     let array = [NonCopy; 1];
1855     let _value = &array[0]; // Borrowing is allowed, unlike moving.
1856 }
1857 ```
1858
1859 Alternatively, if your type implements `Clone` and you need to own the value,
1860 consider borrowing and then cloning:
1861
1862 ```
1863 #[derive(Clone)]
1864 struct NonCopy;
1865
1866 fn main() {
1867     let array = [NonCopy; 1];
1868     // Now you can clone the array element.
1869     let _value = array[0].clone();
1870 }
1871 ```
1872 "##,
1873
1874 E0509: r##"
1875 This error occurs when an attempt is made to move out of a value whose type
1876 implements the `Drop` trait.
1877
1878 Example of erroneous code:
1879
1880 ```compile_fail,E0509
1881 struct FancyNum {
1882     num: usize
1883 }
1884
1885 struct DropStruct {
1886     fancy: FancyNum
1887 }
1888
1889 impl Drop for DropStruct {
1890     fn drop(&mut self) {
1891         // Destruct DropStruct, possibly using FancyNum
1892     }
1893 }
1894
1895 fn main() {
1896     let drop_struct = DropStruct{fancy: FancyNum{num: 5}};
1897     let fancy_field = drop_struct.fancy; // Error E0509
1898     println!("Fancy: {}", fancy_field.num);
1899     // implicit call to `drop_struct.drop()` as drop_struct goes out of scope
1900 }
1901 ```
1902
1903 Here, we tried to move a field out of a struct of type `DropStruct` which
1904 implements the `Drop` trait. However, a struct cannot be dropped if one or
1905 more of its fields have been moved.
1906
1907 Structs implementing the `Drop` trait have an implicit destructor that gets
1908 called when they go out of scope. This destructor may use the fields of the
1909 struct, so moving out of the struct could make it impossible to run the
1910 destructor. Therefore, we must think of all values whose type implements the
1911 `Drop` trait as single units whose fields cannot be moved.
1912
1913 This error can be fixed by creating a reference to the fields of a struct,
1914 enum, or tuple using the `ref` keyword:
1915
1916 ```
1917 struct FancyNum {
1918     num: usize
1919 }
1920
1921 struct DropStruct {
1922     fancy: FancyNum
1923 }
1924
1925 impl Drop for DropStruct {
1926     fn drop(&mut self) {
1927         // Destruct DropStruct, possibly using FancyNum
1928     }
1929 }
1930
1931 fn main() {
1932     let drop_struct = DropStruct{fancy: FancyNum{num: 5}};
1933     let ref fancy_field = drop_struct.fancy; // No more errors!
1934     println!("Fancy: {}", fancy_field.num);
1935     // implicit call to `drop_struct.drop()` as drop_struct goes out of scope
1936 }
1937 ```
1938
1939 Note that this technique can also be used in the arms of a match expression:
1940
1941 ```
1942 struct FancyNum {
1943     num: usize
1944 }
1945
1946 enum DropEnum {
1947     Fancy(FancyNum)
1948 }
1949
1950 impl Drop for DropEnum {
1951     fn drop(&mut self) {
1952         // Destruct DropEnum, possibly using FancyNum
1953     }
1954 }
1955
1956 fn main() {
1957     // Creates and enum of type `DropEnum`, which implements `Drop`
1958     let drop_enum = DropEnum::Fancy(FancyNum{num: 10});
1959     match drop_enum {
1960         // Creates a reference to the inside of `DropEnum::Fancy`
1961         DropEnum::Fancy(ref fancy_field) => // No error!
1962             println!("It was fancy-- {}!", fancy_field.num),
1963     }
1964     // implicit call to `drop_enum.drop()` as drop_enum goes out of scope
1965 }
1966 ```
1967 "##,
1968
1969 E0510: r##"
1970 Cannot mutate place in this match guard.
1971
1972 When matching on a variable it cannot be mutated in the match guards, as this
1973 could cause the match to be non-exhaustive:
1974
1975 ```compile_fail,E0510
1976 let mut x = Some(0);
1977 match x {
1978     None => (),
1979     Some(_) if { x = None; false } => (),
1980     Some(v) => (), // No longer matches
1981 }
1982 ```
1983
1984 Here executing `x = None` would modify the value being matched and require us
1985 to go "back in time" to the `None` arm.
1986 "##,
1987
1988 E0515: r##"
1989 Cannot return value that references local variable
1990
1991 Local variables, function parameters and temporaries are all dropped before the
1992 end of the function body. So a reference to them cannot be returned.
1993
1994 ```compile_fail,E0515
1995 fn get_dangling_reference() -> &'static i32 {
1996     let x = 0;
1997     &x
1998 }
1999 ```
2000
2001 ```compile_fail,E0515
2002 use std::slice::Iter;
2003 fn get_dangling_iterator<'a>() -> Iter<'a, i32> {
2004     let v = vec![1, 2, 3];
2005     v.iter()
2006 }
2007 ```
2008
2009 Consider returning an owned value instead:
2010
2011 ```
2012 use std::vec::IntoIter;
2013
2014 fn get_integer() -> i32 {
2015     let x = 0;
2016     x
2017 }
2018
2019 fn get_owned_iterator() -> IntoIter<i32> {
2020     let v = vec![1, 2, 3];
2021     v.into_iter()
2022 }
2023 ```
2024 "##,
2025
2026 E0524: r##"
2027 A variable which requires unique access is being used in more than one closure
2028 at the same time.
2029
2030 Erroneous code example:
2031
2032 ```compile_fail,E0524
2033 fn set(x: &mut isize) {
2034     *x += 4;
2035 }
2036
2037 fn dragoooon(x: &mut isize) {
2038     let mut c1 = || set(x);
2039     let mut c2 = || set(x); // error!
2040
2041     c2();
2042     c1();
2043 }
2044 ```
2045
2046 To solve this issue, multiple solutions are available. First, is it required
2047 for this variable to be used in more than one closure at a time? If it is the
2048 case, use reference counted types such as `Rc` (or `Arc` if it runs
2049 concurrently):
2050
2051 ```
2052 use std::rc::Rc;
2053 use std::cell::RefCell;
2054
2055 fn set(x: &mut isize) {
2056     *x += 4;
2057 }
2058
2059 fn dragoooon(x: &mut isize) {
2060     let x = Rc::new(RefCell::new(x));
2061     let y = Rc::clone(&x);
2062     let mut c1 = || { let mut x2 = x.borrow_mut(); set(&mut x2); };
2063     let mut c2 = || { let mut x2 = y.borrow_mut(); set(&mut x2); }; // ok!
2064
2065     c2();
2066     c1();
2067 }
2068 ```
2069
2070 If not, just run closures one at a time:
2071
2072 ```
2073 fn set(x: &mut isize) {
2074     *x += 4;
2075 }
2076
2077 fn dragoooon(x: &mut isize) {
2078     { // This block isn't necessary since non-lexical lifetimes, it's just to
2079       // make it more clear.
2080         let mut c1 = || set(&mut *x);
2081         c1();
2082     } // `c1` has been dropped here so we're free to use `x` again!
2083     let mut c2 = || set(&mut *x);
2084     c2();
2085 }
2086 ```
2087 "##,
2088
2089 E0579: r##"
2090 When matching against an exclusive range, the compiler verifies that the range
2091 is non-empty. Exclusive range patterns include the start point but not the end
2092 point, so this is equivalent to requiring the start of the range to be less
2093 than the end of the range.
2094
2095 For example:
2096
2097 ```compile_fail
2098 match 5u32 {
2099     // This range is ok, albeit pointless.
2100     1 .. 2 => {}
2101     // This range is empty, and the compiler can tell.
2102     5 .. 5 => {}
2103 }
2104 ```
2105 "##,
2106
2107 E0595: r##"
2108 #### Note: this error code is no longer emitted by the compiler.
2109
2110 Closures cannot mutate immutable captured variables.
2111
2112 Erroneous code example:
2113
2114 ```compile_fail,E0594
2115 let x = 3; // error: closure cannot assign to immutable local variable `x`
2116 let mut c = || { x += 1 };
2117 ```
2118
2119 Make the variable binding mutable:
2120
2121 ```
2122 let mut x = 3; // ok!
2123 let mut c = || { x += 1 };
2124 ```
2125 "##,
2126
2127 E0596: r##"
2128 This error occurs because you tried to mutably borrow a non-mutable variable.
2129
2130 Example of erroneous code:
2131
2132 ```compile_fail,E0596
2133 let x = 1;
2134 let y = &mut x; // error: cannot borrow mutably
2135 ```
2136
2137 In here, `x` isn't mutable, so when we try to mutably borrow it in `y`, it
2138 fails. To fix this error, you need to make `x` mutable:
2139
2140 ```
2141 let mut x = 1;
2142 let y = &mut x; // ok!
2143 ```
2144 "##,
2145
2146 E0597: r##"
2147 This error occurs because a value was dropped while it was still borrowed
2148
2149 Example of erroneous code:
2150
2151 ```compile_fail,E0597
2152 struct Foo<'a> {
2153     x: Option<&'a u32>,
2154 }
2155
2156 let mut x = Foo { x: None };
2157 {
2158     let y = 0;
2159     x.x = Some(&y); // error: `y` does not live long enough
2160 }
2161 println!("{:?}", x.x);
2162 ```
2163
2164 In here, `y` is dropped at the end of the inner scope, but it is borrowed by
2165 `x` until the `println`. To fix the previous example, just remove the scope
2166 so that `y` isn't dropped until after the println
2167
2168 ```
2169 struct Foo<'a> {
2170     x: Option<&'a u32>,
2171 }
2172
2173 let mut x = Foo { x: None };
2174
2175 let y = 0;
2176 x.x = Some(&y);
2177
2178 println!("{:?}", x.x);
2179 ```
2180 "##,
2181
2182 E0626: r##"
2183 This error occurs because a borrow in a generator persists across a
2184 yield point.
2185
2186 ```compile_fail,E0626
2187 # #![feature(generators, generator_trait, pin)]
2188 # use std::ops::Generator;
2189 # use std::pin::Pin;
2190 let mut b = || {
2191     let a = &String::new(); // <-- This borrow...
2192     yield (); // ...is still in scope here, when the yield occurs.
2193     println!("{}", a);
2194 };
2195 Pin::new(&mut b).resume();
2196 ```
2197
2198 At present, it is not permitted to have a yield that occurs while a
2199 borrow is still in scope. To resolve this error, the borrow must
2200 either be "contained" to a smaller scope that does not overlap the
2201 yield or else eliminated in another way. So, for example, we might
2202 resolve the previous example by removing the borrow and just storing
2203 the integer by value:
2204
2205 ```
2206 # #![feature(generators, generator_trait, pin)]
2207 # use std::ops::Generator;
2208 # use std::pin::Pin;
2209 let mut b = || {
2210     let a = 3;
2211     yield ();
2212     println!("{}", a);
2213 };
2214 Pin::new(&mut b).resume();
2215 ```
2216
2217 This is a very simple case, of course. In more complex cases, we may
2218 wish to have more than one reference to the value that was borrowed --
2219 in those cases, something like the `Rc` or `Arc` types may be useful.
2220
2221 This error also frequently arises with iteration:
2222
2223 ```compile_fail,E0626
2224 # #![feature(generators, generator_trait, pin)]
2225 # use std::ops::Generator;
2226 # use std::pin::Pin;
2227 let mut b = || {
2228   let v = vec![1,2,3];
2229   for &x in &v { // <-- borrow of `v` is still in scope...
2230     yield x; // ...when this yield occurs.
2231   }
2232 };
2233 Pin::new(&mut b).resume();
2234 ```
2235
2236 Such cases can sometimes be resolved by iterating "by value" (or using
2237 `into_iter()`) to avoid borrowing:
2238
2239 ```
2240 # #![feature(generators, generator_trait, pin)]
2241 # use std::ops::Generator;
2242 # use std::pin::Pin;
2243 let mut b = || {
2244   let v = vec![1,2,3];
2245   for x in v { // <-- Take ownership of the values instead!
2246     yield x; // <-- Now yield is OK.
2247   }
2248 };
2249 Pin::new(&mut b).resume();
2250 ```
2251
2252 If taking ownership is not an option, using indices can work too:
2253
2254 ```
2255 # #![feature(generators, generator_trait, pin)]
2256 # use std::ops::Generator;
2257 # use std::pin::Pin;
2258 let mut b = || {
2259   let v = vec![1,2,3];
2260   let len = v.len(); // (*)
2261   for i in 0..len {
2262     let x = v[i]; // (*)
2263     yield x; // <-- Now yield is OK.
2264   }
2265 };
2266 Pin::new(&mut b).resume();
2267
2268 // (*) -- Unfortunately, these temporaries are currently required.
2269 // See <https://github.com/rust-lang/rust/issues/43122>.
2270 ```
2271 "##,
2272
2273 E0712: r##"
2274 This error occurs because a borrow of a thread-local variable was made inside a
2275 function which outlived the lifetime of the function.
2276
2277 Example of erroneous code:
2278
2279 ```compile_fail,E0712
2280 #![feature(thread_local)]
2281
2282 #[thread_local]
2283 static FOO: u8 = 3;
2284
2285 fn main() {
2286     let a = &FOO; // error: thread-local variable borrowed past end of function
2287
2288     std::thread::spawn(move || {
2289         println!("{}", a);
2290     });
2291 }
2292 ```
2293 "##,
2294
2295 E0713: r##"
2296 This error occurs when an attempt is made to borrow state past the end of the
2297 lifetime of a type that implements the `Drop` trait.
2298
2299 Example of erroneous code:
2300
2301 ```compile_fail,E0713
2302 #![feature(nll)]
2303
2304 pub struct S<'a> { data: &'a mut String }
2305
2306 impl<'a> Drop for S<'a> {
2307     fn drop(&mut self) { self.data.push_str("being dropped"); }
2308 }
2309
2310 fn demo<'a>(s: S<'a>) -> &'a mut String { let p = &mut *s.data; p }
2311 ```
2312
2313 Here, `demo` tries to borrow the string data held within its
2314 argument `s` and then return that borrow. However, `S` is
2315 declared as implementing `Drop`.
2316
2317 Structs implementing the `Drop` trait have an implicit destructor that
2318 gets called when they go out of scope. This destructor gets exclusive
2319 access to the fields of the struct when it runs.
2320
2321 This means that when `s` reaches the end of `demo`, its destructor
2322 gets exclusive access to its `&mut`-borrowed string data.  allowing
2323 another borrow of that string data (`p`), to exist across the drop of
2324 `s` would be a violation of the principle that `&mut`-borrows have
2325 exclusive, unaliased access to their referenced data.
2326
2327 This error can be fixed by changing `demo` so that the destructor does
2328 not run while the string-data is borrowed; for example by taking `S`
2329 by reference:
2330
2331 ```
2332 pub struct S<'a> { data: &'a mut String }
2333
2334 impl<'a> Drop for S<'a> {
2335     fn drop(&mut self) { self.data.push_str("being dropped"); }
2336 }
2337
2338 fn demo<'a>(s: &'a mut S<'a>) -> &'a mut String { let p = &mut *(*s).data; p }
2339 ```
2340
2341 Note that this approach needs a reference to S with lifetime `'a`.
2342 Nothing shorter than `'a` will suffice: a shorter lifetime would imply
2343 that after `demo` finishes executing, something else (such as the
2344 destructor!) could access `s.data` after the end of that shorter
2345 lifetime, which would again violate the `&mut`-borrow's exclusive
2346 access.
2347 "##,
2348
2349 E0716: r##"
2350 This error indicates that a temporary value is being dropped
2351 while a borrow is still in active use.
2352
2353 Erroneous code example:
2354
2355 ```compile_fail,E0716
2356 fn foo() -> i32 { 22 }
2357 fn bar(x: &i32) -> &i32 { x }
2358 let p = bar(&foo());
2359          // ------ creates a temporary
2360 let q = *p;
2361 ```
2362
2363 Here, the expression `&foo()` is borrowing the expression
2364 `foo()`. As `foo()` is a call to a function, and not the name of
2365 a variable, this creates a **temporary** -- that temporary stores
2366 the return value from `foo()` so that it can be borrowed.
2367 You could imagine that `let p = bar(&foo());` is equivalent
2368 to this:
2369
2370 ```compile_fail,E0597
2371 # fn foo() -> i32 { 22 }
2372 # fn bar(x: &i32) -> &i32 { x }
2373 let p = {
2374   let tmp = foo(); // the temporary
2375   bar(&tmp)
2376 }; // <-- tmp is freed as we exit this block
2377 let q = p;
2378 ```
2379
2380 Whenever a temporary is created, it is automatically dropped (freed)
2381 according to fixed rules. Ordinarily, the temporary is dropped
2382 at the end of the enclosing statement -- in this case, after the `let`.
2383 This is illustrated in the example above by showing that `tmp` would
2384 be freed as we exit the block.
2385
2386 To fix this problem, you need to create a local variable
2387 to store the value in rather than relying on a temporary.
2388 For example, you might change the original program to
2389 the following:
2390
2391 ```
2392 fn foo() -> i32 { 22 }
2393 fn bar(x: &i32) -> &i32 { x }
2394 let value = foo(); // dropped at the end of the enclosing block
2395 let p = bar(&value);
2396 let q = *p;
2397 ```
2398
2399 By introducing the explicit `let value`, we allocate storage
2400 that will last until the end of the enclosing block (when `value`
2401 goes out of scope). When we borrow `&value`, we are borrowing a
2402 local variable that already exists, and hence no temporary is created.
2403
2404 Temporaries are not always dropped at the end of the enclosing
2405 statement. In simple cases where the `&` expression is immediately
2406 stored into a variable, the compiler will automatically extend
2407 the lifetime of the temporary until the end of the enclosing
2408 block. Therefore, an alternative way to fix the original
2409 program is to write `let tmp = &foo()` and not `let tmp = foo()`:
2410
2411 ```
2412 fn foo() -> i32 { 22 }
2413 fn bar(x: &i32) -> &i32 { x }
2414 let value = &foo();
2415 let p = bar(value);
2416 let q = *p;
2417 ```
2418
2419 Here, we are still borrowing `foo()`, but as the borrow is assigned
2420 directly into a variable, the temporary will not be dropped until
2421 the end of the enclosing block. Similar rules apply when temporaries
2422 are stored into aggregate structures like a tuple or struct:
2423
2424 ```
2425 // Here, two temporaries are created, but
2426 // as they are stored directly into `value`,
2427 // they are not dropped until the end of the
2428 // enclosing block.
2429 fn foo() -> i32 { 22 }
2430 let value = (&foo(), &foo());
2431 ```
2432 "##,
2433
2434 E0723: r##"
2435 An feature unstable in `const` contexts was used.
2436
2437 Erroneous code example:
2438
2439 ```compile_fail,E0723
2440 trait T {}
2441
2442 impl T for () {}
2443
2444 const fn foo() -> impl T { // error: `impl Trait` in const fn is unstable
2445     ()
2446 }
2447 ```
2448
2449 To enable this feature on a nightly version of rustc, add the `const_fn`
2450 feature flag:
2451
2452 ```
2453 #![feature(const_fn)]
2454
2455 trait T {}
2456
2457 impl T for () {}
2458
2459 const fn foo() -> impl T {
2460     ()
2461 }
2462 ```
2463 "##,
2464
2465 E0729: r##"
2466 Support for Non-Lexical Lifetimes (NLL) has been included in the Rust compiler
2467 since 1.31, and has been enabled on the 2015 edition since 1.36. The new borrow
2468 checker for NLL uncovered some bugs in the old borrow checker, which in some
2469 cases allowed unsound code to compile, resulting in memory safety issues.
2470
2471 ### What do I do?
2472
2473 Change your code so the warning does no longer trigger. For backwards
2474 compatibility, this unsound code may still compile (with a warning) right now.
2475 However, at some point in the future, the compiler will no longer accept this
2476 code and will throw a hard error.
2477
2478 ### Shouldn't you fix the old borrow checker?
2479
2480 The old borrow checker has known soundness issues that are basically impossible
2481 to fix. The new NLL-based borrow checker is the fix.
2482
2483 ### Can I turn these warnings into errors by denying a lint?
2484
2485 No.
2486
2487 ### When are these warnings going to turn into errors?
2488
2489 No formal timeline for turning the warnings into errors has been set. See
2490 [GitHub issue 58781](https://github.com/rust-lang/rust/issues/58781) for more
2491 information.
2492
2493 ### Why do I get this message with code that doesn't involve borrowing?
2494
2495 There are some known bugs that trigger this message.
2496 "##,
2497
2498 ;
2499
2500 //  E0008, // cannot bind by-move into a pattern guard
2501 //  E0298, // cannot compare constants
2502 //  E0299, // mismatched types between arms
2503 //  E0471, // constant evaluation error (in pattern)
2504 //  E0385, // {} in an aliasable location
2505     E0521, // borrowed data escapes outside of closure
2506     E0526, // shuffle indices are not constant
2507     E0594, // cannot assign to {}
2508 //  E0598, // lifetime of {} is too short to guarantee its contents can be...
2509     E0625, // thread-local statics cannot be accessed at compile-time
2510 }