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