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