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