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.
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.
11 #![allow(non_snake_case)]
13 register_long_diagnostics! {
17 #### Note: this error code is no longer emitted by the compiler.
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.
23 This means that perhaps some of the preceding patterns are too general, this
24 one is too specific or the ordering is incorrect.
26 For example, the following `match` block has too many arms:
30 Some(bar) => {/* ... */}
31 x => {/* ... */} // This handles the `None` case
32 _ => {/* ... */} // All possible cases have already been handled
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.
39 Ensure the ordering of the match arm is correct and remove any superfluous
44 #### Note: this error code is no longer emitted by the compiler.
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.
52 An example of an empty type is `enum Empty { }`. So, the following will work:
67 fn foo(x: Option<String>) {
76 This error indicates that the compiler cannot guarantee a matching pattern for
77 one or more possible inputs to a match expression. Guaranteed matches are
78 required in order to assign values to match expressions, or alternatively,
79 determine the flow of execution. Erroneous code example:
87 let x = Terminator::HastaLaVistaBaby;
89 match x { // error: non-exhaustive patterns: `HastaLaVistaBaby` not covered
90 Terminator::TalkToMyHand => {}
94 If you encounter this error you must alter your patterns so that every possible
95 value of the input type is matched. For types with a small number of variants
96 (like enums) you should probably cover all cases explicitly. Alternatively, the
97 underscore `_` wildcard pattern can be added after all other patterns to match
98 "anything else". Example:
106 let x = Terminator::HastaLaVistaBaby;
109 Terminator::TalkToMyHand => {}
110 Terminator::HastaLaVistaBaby => {}
116 Terminator::TalkToMyHand => {}
123 Patterns used to bind names must be irrefutable, that is, they must guarantee
124 that a name will be extracted in all cases. Erroneous code example:
126 ```compile_fail,E0005
129 // error: refutable pattern in local binding: `None` not covered
132 If you encounter this error you probably need to use a `match` or `if let` to
133 deal with the possibility of failure. Example:
154 This error indicates that the bindings in a match arm would require a value to
155 be moved into more than one location, thus violating unique ownership. Code
156 like the following is invalid as it requires the entire `Option<String>` to be
157 moved into a variable called `op_string` while simultaneously requiring the
158 inner `String` to be moved into a variable called `s`.
160 ```compile_fail,E0007
161 let x = Some("s".to_string());
164 op_string @ Some(s) => {}, // error: cannot bind by-move with sub-bindings
169 See also the error E0303.
173 Names bound in match arms retain their type in pattern guards. As such, if a
174 name is bound by move in a pattern, it should also be moved to wherever it is
175 referenced in the pattern guard code. Doing so however would prevent the name
176 from being available in the body of the match arm. Consider the following:
178 ```compile_fail,E0008
179 match Some("hi".to_string()) {
180 Some(s) if s.len() == 0 => {}, // use s.
185 The variable `s` has type `String`, and its use in the guard is as a variable of
186 type `String`. The guard code effectively executes in a separate scope to the
187 body of the arm, so the value would be moved into this anonymous scope and
188 therefore becomes unavailable in the body of the arm.
190 The problem above can be solved by using the `ref` keyword.
193 match Some("hi".to_string()) {
194 Some(ref s) if s.len() == 0 => {},
199 Though this example seems innocuous and easy to solve, the problem becomes clear
200 when it encounters functions which consume the value:
202 ```compile_fail,E0008
206 fn consume(self) -> usize {
214 Some(y) if y.consume() > 0 => {}
220 In this situation, even the `ref` keyword cannot solve it, since borrowed
221 content cannot be moved. This problem cannot be solved generally. If the value
222 can be cloned, here is a not-so-specific solution:
229 fn consume(self) -> usize {
237 Some(ref y) if y.clone().consume() > 0 => {}
243 If the value will be consumed in the pattern guard, using its clone will not
244 move its ownership, so the code works.
248 In a pattern, all values that don't implement the `Copy` trait have to be bound
249 the same way. The goal here is to avoid binding simultaneously by-move and
252 This limitation may be removed in a future version of Rust.
254 Erroneous code example:
256 ```compile_fail,E0009
259 let x = Some((X { x: () }, X { x: () }));
261 Some((y, ref z)) => {}, // error: cannot bind by-move and by-ref in the
267 You have two solutions:
269 Solution #1: Bind the pattern's values the same way.
274 let x = Some((X { x: () }, X { x: () }));
276 Some((ref y, ref z)) => {},
277 // or Some((y, z)) => {}
282 Solution #2: Implement the `Copy` trait for the `X` structure.
284 However, please keep in mind that the first solution should be preferred.
287 #[derive(Clone, Copy)]
290 let x = Some((X { x: () }, X { x: () }));
292 Some((y, ref z)) => {},
299 When matching against a range, the compiler verifies that the range is
300 non-empty. Range patterns include both end-points, so this is equivalent to
301 requiring the start of the range to be less than or equal to the end of the
308 // This range is ok, albeit pointless.
310 // This range is empty, and the compiler can tell.
317 `const` and `static` mean different things. A `const` is a compile-time
318 constant, an alias for a literal value. This property means you can match it
319 directly within a pattern.
321 The `static` keyword, on the other hand, guarantees a fixed location in memory.
322 This does not always mean that the value is constant. For example, a global
323 mutex can be declared `static` as well.
325 If you want to match against a `static`, consider using a guard instead:
328 static FORTY_TWO: i32 = 42;
331 Some(x) if x == FORTY_TWO => {}
338 An if-let pattern attempts to match the pattern, and enters the body if the
339 match was successful. If the match is irrefutable (when it cannot fail to
340 match), use a regular `let`-binding instead. For instance:
342 ```compile_fail,E0162
343 struct Irrefutable(i32);
344 let irr = Irrefutable(0);
346 // This fails to compile because the match is irrefutable.
347 if let Irrefutable(x) = irr {
348 // This body will always be executed.
356 struct Irrefutable(i32);
357 let irr = Irrefutable(0);
359 let Irrefutable(x) = irr;
365 A while-let pattern attempts to match the pattern, and enters the body if the
366 match was successful. If the match is irrefutable (when it cannot fail to
367 match), use a regular `let`-binding inside a `loop` instead. For instance:
369 ```compile_fail,E0165
370 struct Irrefutable(i32);
371 let irr = Irrefutable(0);
373 // This fails to compile because the match is irrefutable.
374 while let Irrefutable(x) = irr {
382 struct Irrefutable(i32);
383 let irr = Irrefutable(0);
386 let Irrefutable(x) = irr;
393 Enum variants are qualified by default. For example, given this type:
402 You would match it using:
418 If you don't qualify the names, the code will bind new variables named "GET" and
419 "POST" instead. This behavior is likely not what you want, so `rustc` warns when
422 Qualified names are good practice, and most code works well with them. But if
423 you prefer them unqualified, you can import the variants into scope:
427 enum Method { GET, POST }
431 If you want others to be able to import variants from your module directly, use
436 pub enum Method { GET, POST }
443 #### Note: this error code is no longer emitted by the compiler.
445 Patterns used to bind names must be irrefutable. That is, they must guarantee
446 that a name will be extracted in all cases. Instead of pattern matching the
447 loop variable, consider using a `match` or `if let` inside the loop body. For
450 ```compile_fail,E0005
451 let xs : Vec<Option<i32>> = vec![Some(1), None];
453 // This fails because `None` is not covered.
459 Match inside the loop instead:
462 let xs : Vec<Option<i32>> = vec![Some(1), None];
475 let xs : Vec<Option<i32>> = vec![Some(1), None];
478 if let Some(x) = item {
486 Mutable borrows are not allowed in pattern guards, because matching cannot have
487 side effects. Side effects could alter the matched object or the environment
488 on which the match depends in such a way, that the match would not be
489 exhaustive. For instance, the following would not match any arm if mutable
490 borrows were allowed:
492 ```compile_fail,E0301
495 option if option.take().is_none() => {
496 /* impossible, option is `Some` */
498 Some(_) => { } // When the previous match failed, the option became `None`.
504 Assignments are not allowed in pattern guards, because matching cannot have
505 side effects. Side effects could alter the matched object or the environment
506 on which the match depends in such a way, that the match would not be
507 exhaustive. For instance, the following would not match any arm if assignments
510 ```compile_fail,E0302
513 option if { option = None; false } => { },
514 Some(_) => { } // When the previous match failed, the option became `None`.
520 In certain cases it is possible for sub-bindings to violate memory safety.
521 Updates to the borrow checker in a future version of Rust may remove this
522 restriction, but for now patterns must be rewritten without sub-bindings.
526 ```compile_fail,E0303
527 match Some("hi".to_string()) {
528 ref op_string_ref @ Some(s) => {},
536 match Some("hi".to_string()) {
538 let op_string_ref = &Some(s);
545 The `op_string_ref` binding has type `&Option<&String>` in both cases.
547 See also https://github.com/rust-lang/rust/issues/14587
551 The value of statics and constants must be known at compile time, and they live
552 for the entire lifetime of a program. Creating a boxed value allocates memory on
553 the heap at runtime, and therefore cannot be done at compile time. Erroneous
556 ```compile_fail,E0010
557 #![feature(box_syntax)]
559 const CON : Box<i32> = box 0;
564 Static and const variables can refer to other const variables. But a const
565 variable cannot refer to a static variable. For example, `Y` cannot refer to
568 ```compile_fail,E0013
573 To fix this, the value can be extracted as a const and then used:
582 // FIXME(#24111) Change the language here when const fn stabilizes
584 The only functions that can be called in static or constant expressions are
585 `const` functions, and struct/enum constructors. `const` functions are only
586 available on a nightly compiler. Rust currently does not support more general
587 compile-time function execution.
590 const FOO: Option<u8> = Some(1); // enum constructor
592 const BAR: Bar = Bar {x: 1}; // struct constructor
595 See [RFC 911] for more details on the design of `const fn`s.
597 [RFC 911]: https://github.com/rust-lang/rfcs/blob/master/text/0911-const-fn.md
601 References in statics and constants may only refer to immutable values.
602 Erroneous code example:
604 ```compile_fail,E0017
608 // these three are not allowed:
609 const CR: &'static mut i32 = &mut C;
610 static STATIC_REF: &'static mut i32 = &mut X;
611 static CONST_REF: &'static mut i32 = &mut C;
614 Statics are shared everywhere, and if they refer to mutable data one might
615 violate memory safety since holding multiple mutable references to shared data
618 If you really want global mutable state, try using `static mut` or a global
623 A function call isn't allowed in the const's initialization expression
624 because the expression's value must be known at compile-time. Erroneous code
633 fn test(&self) -> i32 {
639 const FOO: Test = Test::V1;
641 const A: i32 = FOO.test(); // You can't call Test::func() here!
645 Remember: you can't use a function call inside a const's initialization
646 expression! However, you can totally use it anywhere else:
654 fn func(&self) -> i32 {
660 const FOO: Test = Test::V1;
662 FOO.func(); // here is good
663 let x = FOO.func(); // or even here!
669 Constant functions are not allowed to mutate anything. Thus, binding to an
670 argument with a mutable pattern is not allowed. For example,
673 const fn foo(mut x: u8) {
678 Is incorrect because the function body may not mutate `x`.
680 Remove any mutable bindings from the argument list to fix this error. In case
681 you need to mutate the argument, try lazily initializing a global variable
682 instead of using a `const fn`, or refactoring the code to a functional style to
683 avoid mutation if possible.
687 Unsafe code was used outside of an unsafe function or block.
689 Erroneous code example:
691 ```compile_fail,E0133
692 unsafe fn f() { return; } // This is the unsafe code
695 f(); // error: call to unsafe function requires unsafe function or block
699 Using unsafe functionality is potentially dangerous and disallowed by safety
702 * Dereferencing raw pointers
703 * Calling functions via FFI
704 * Calling functions marked unsafe
706 These safety checks can be relaxed for a section of the code by wrapping the
707 unsafe instructions with an `unsafe` block. For instance:
710 unsafe fn f() { return; }
713 unsafe { f(); } // ok!
717 See also https://doc.rust-lang.org/book/first-edition/unsafe.html
721 This error occurs when an attempt is made to use data captured by a closure,
722 when that data may no longer exist. It's most commonly seen when attempting to
725 ```compile_fail,E0373
726 fn foo() -> Box<Fn(u32) -> u32> {
732 Notice that `x` is stack-allocated by `foo()`. By default, Rust captures
733 closed-over data by reference. This means that once `foo()` returns, `x` no
734 longer exists. An attempt to access `x` within the closure would thus be
737 Another situation where this might be encountered is when spawning threads:
739 ```compile_fail,E0373
744 let thr = std::thread::spawn(|| {
750 Since our new thread runs in parallel, the stack frame containing `x` and `y`
751 may well have disappeared by the time we try to use them. Even if we call
752 `thr.join()` within foo (which blocks until `thr` has completed, ensuring the
753 stack frame won't disappear), we will not succeed: the compiler cannot prove
754 that this behaviour is safe, and so won't let us do it.
756 The solution to this problem is usually to switch to using a `move` closure.
757 This approach moves (or copies, where possible) data into the closure, rather
758 than taking references to it. For example:
761 fn foo() -> Box<Fn(u32) -> u32> {
763 Box::new(move |y| x + y)
767 Now that the closure has its own copy of the data, there's no need to worry
772 It is not allowed to use or capture an uninitialized variable. For example:
774 ```compile_fail,E0381
777 let y = x; // error, use of possibly uninitialized variable
781 To fix this, ensure that any declared variables are initialized before being
793 This error occurs when an attempt is made to use a variable after its contents
794 have been moved elsewhere. For example:
796 ```compile_fail,E0382
797 struct MyStruct { s: u32 }
800 let mut x = MyStruct{ s: 5u32 };
807 Since `MyStruct` is a type that is not marked `Copy`, the data gets moved out
808 of `x` when we set `y`. This is fundamental to Rust's ownership system: outside
809 of workarounds like `Rc`, a value cannot be owned by more than one variable.
811 Sometimes we don't need to move the value. Using a reference, we can let another
812 function borrow the value without changing its ownership. In the example below,
813 we don't actually have to move our string to `calculate_length`, we can give it
814 a reference to it with `&` instead.
818 let s1 = String::from("hello");
820 let len = calculate_length(&s1);
822 println!("The length of '{}' is {}.", s1, len);
825 fn calculate_length(s: &String) -> usize {
830 A mutable reference can be created with `&mut`.
832 Sometimes we don't want a reference, but a duplicate. All types marked `Clone`
833 can be duplicated by calling `.clone()`. Subsequent changes to a clone do not
834 affect the original variable.
836 Most types in the standard library are marked `Clone`. The example below
837 demonstrates using `clone()` on a string. `s1` is first set to "many", and then
838 copied to `s2`. Then the first character of `s1` is removed, without affecting
839 `s2`. "any many" is printed to the console.
843 let mut s1 = String::from("many");
846 println!("{} {}", s1, s2);
850 If we control the definition of a type, we can implement `Clone` on it ourselves
851 with `#[derive(Clone)]`.
853 Some types have no ownership semantics at all and are trivial to duplicate. An
854 example is `i32` and the other number types. We don't have to call `.clone()` to
855 clone them, because they are marked `Copy` in addition to `Clone`. Implicit
856 cloning is more convenient in this case. We can mark our own types `Copy` if
857 all their members also are marked `Copy`.
859 In the example below, we implement a `Point` type. Because it only stores two
860 integers, we opt-out of ownership semantics with `Copy`. Then we can
861 `let p2 = p1` without `p1` being moved.
864 #[derive(Copy, Clone)]
865 struct Point { x: i32, y: i32 }
868 let mut p1 = Point{ x: -1, y: 2 };
871 println!("p1: {}, {}", p1.x, p1.y);
872 println!("p2: {}, {}", p2.x, p2.y);
876 Alternatively, if we don't control the struct's definition, or mutable shared
877 ownership is truly required, we can use `Rc` and `RefCell`:
880 use std::cell::RefCell;
883 struct MyStruct { s: u32 }
886 let mut x = Rc::new(RefCell::new(MyStruct{ s: 5u32 }));
888 x.borrow_mut().s = 6;
889 println!("{}", x.borrow().s);
893 With this approach, x and y share ownership of the data via the `Rc` (reference
894 count type). `RefCell` essentially performs runtime borrow checking: ensuring
895 that at most one writer or multiple readers can access the data at any one time.
897 If you wish to learn more about ownership in Rust, start with the chapter in the
900 https://doc.rust-lang.org/book/first-edition/ownership.html
904 This error occurs when an attempt is made to partially reinitialize a
905 structure that is currently uninitialized.
907 For example, this can happen when a drop has taken place:
909 ```compile_fail,E0383
914 fn drop(&mut self) { /* ... */ }
917 let mut x = Foo { a: 1 };
918 drop(x); // `x` is now uninitialized
919 x.a = 2; // error, partial reinitialization of uninitialized structure `t`
922 This error can be fixed by fully reinitializing the structure in question:
929 fn drop(&mut self) { /* ... */ }
932 let mut x = Foo { a: 1 };
939 This error occurs when an attempt is made to reassign an immutable variable.
942 ```compile_fail,E0384
945 x = 5; // error, reassignment of immutable variable
949 By default, variables in Rust are immutable. To fix this error, add the keyword
950 `mut` after the keyword `let` when declaring the variable. For example:
961 This error occurs when an attempt is made to mutate the target of a mutable
962 reference stored inside an immutable container.
964 For example, this can happen when storing a `&mut` inside an immutable `Box`:
966 ```compile_fail,E0386
968 let y: Box<_> = Box::new(&mut x);
969 **y = 2; // error, cannot assign to data in an immutable container
972 This error can be fixed by making the container mutable:
976 let mut y: Box<_> = Box::new(&mut x);
980 It can also be fixed by using a type with interior mutability, such as `Cell`
987 let y: Box<Cell<_>> = Box::new(Cell::new(x));
993 This error occurs when an attempt is made to mutate or mutably reference data
994 that a closure has captured immutably. Examples of this error are shown below:
996 ```compile_fail,E0387
997 // Accepts a function or a closure that captures its environment immutably.
998 // Closures passed to foo will not be able to mutate their closed-over state.
999 fn foo<F: Fn()>(f: F) { }
1001 // Attempts to mutate closed-over data. Error message reads:
1002 // `cannot assign to data in a captured outer variable...`
1008 // Attempts to take a mutable reference to closed-over data. Error message
1009 // reads: `cannot borrow data mutably in a captured outer variable...`
1012 foo(|| { let y = &mut x; });
1016 The problem here is that foo is defined as accepting a parameter of type `Fn`.
1017 Closures passed into foo will thus be inferred to be of type `Fn`, meaning that
1018 they capture their context immutably.
1020 If the definition of `foo` is under your control, the simplest solution is to
1021 capture the data mutably. This can be done by defining `foo` to take FnMut
1025 fn foo<F: FnMut()>(f: F) { }
1028 Alternatively, we can consider using the `Cell` and `RefCell` types to achieve
1029 interior mutability through a shared reference. Our example's `mutable`
1030 function could be redefined as below:
1033 use std::cell::Cell;
1035 fn foo<F: Fn()>(f: F) { }
1038 let x = Cell::new(0u32);
1043 You can read more about cell types in the API documentation:
1045 https://doc.rust-lang.org/std/cell/
1049 E0388 was removed and is no longer issued.
1053 An attempt was made to mutate data using a non-mutable reference. This
1054 commonly occurs when attempting to assign to a non-mutable reference of a
1055 mutable reference (`&(&mut T)`).
1057 Example of erroneous code:
1059 ```compile_fail,E0389
1065 let mut fancy = FancyNum{ num: 5 };
1066 let fancy_ref = &(&mut fancy);
1067 fancy_ref.num = 6; // error: cannot assign to data in a `&` reference
1068 println!("{}", fancy_ref.num);
1072 Here, `&mut fancy` is mutable, but `&(&mut fancy)` is not. Creating an
1073 immutable reference to a value borrows it immutably. There can be multiple
1074 references of type `&(&mut T)` that point to the same value, so they must be
1075 immutable to prevent multiple mutable references to the same value.
1077 To fix this, either remove the outer reference:
1085 let mut fancy = FancyNum{ num: 5 };
1087 let fancy_ref = &mut fancy;
1088 // `fancy_ref` is now &mut FancyNum, rather than &(&mut FancyNum)
1090 fancy_ref.num = 6; // No error!
1092 println!("{}", fancy_ref.num);
1096 Or make the outer reference mutable:
1104 let mut fancy = FancyNum{ num: 5 };
1106 let fancy_ref = &mut (&mut fancy);
1107 // `fancy_ref` is now &mut(&mut FancyNum), rather than &(&mut FancyNum)
1109 fancy_ref.num = 6; // No error!
1111 println!("{}", fancy_ref.num);
1117 A value was moved. However, its size was not known at compile time, and only
1118 values of a known size can be moved.
1120 Erroneous code example:
1123 #![feature(box_syntax)]
1126 let array: &[isize] = &[1, 2, 3];
1127 let _x: Box<[isize]> = box *array;
1128 // error: cannot move a value of type [isize]: the size of [isize] cannot
1129 // be statically determined
1133 In Rust, you can only move a value when its size is known at compile time.
1135 To work around this restriction, consider "hiding" the value behind a reference:
1136 either `&x` or `&mut x`. Since a reference has a fixed size, this lets you move
1137 it around as usual. Example:
1140 #![feature(box_syntax)]
1143 let array: &[isize] = &[1, 2, 3];
1144 let _x: Box<&[isize]> = box array; // ok!
1150 A borrow of a constant containing interior mutability was attempted. Erroneous
1153 ```compile_fail,E0492
1154 use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT};
1156 const A: AtomicUsize = ATOMIC_USIZE_INIT;
1157 static B: &'static AtomicUsize = &A;
1158 // error: cannot borrow a constant which may contain interior mutability,
1159 // create a static instead
1162 A `const` represents a constant value that should never change. If one takes
1163 a `&` reference to the constant, then one is taking a pointer to some memory
1164 location containing the value. Normally this is perfectly fine: most values
1165 can't be changed via a shared `&` pointer, but interior mutability would allow
1166 it. That is, a constant value could be mutated. On the other hand, a `static` is
1167 explicitly a single memory location, which can be mutated at will.
1169 So, in order to solve this error, either use statics which are `Sync`:
1172 use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT};
1174 static A: AtomicUsize = ATOMIC_USIZE_INIT;
1175 static B: &'static AtomicUsize = &A; // ok!
1178 You can also have this error while using a cell type:
1180 ```compile_fail,E0492
1181 use std::cell::Cell;
1183 const A: Cell<usize> = Cell::new(1);
1184 const B: &'static Cell<usize> = &A;
1185 // error: cannot borrow a constant which may contain interior mutability,
1186 // create a static instead
1189 struct C { a: Cell<usize> }
1191 const D: C = C { a: Cell::new(1) };
1192 const E: &'static Cell<usize> = &D.a; // error
1195 const F: &'static C = &D; // error
1198 This is because cell types do operations that are not thread-safe. Due to this,
1199 they don't implement Sync and thus can't be placed in statics.
1201 However, if you still wish to use these types, you can achieve this by an unsafe
1205 use std::cell::Cell;
1206 use std::marker::Sync;
1208 struct NotThreadSafe<T> {
1212 unsafe impl<T> Sync for NotThreadSafe<T> {}
1214 static A: NotThreadSafe<usize> = NotThreadSafe { value : Cell::new(1) };
1215 static B: &'static NotThreadSafe<usize> = &A; // ok!
1218 Remember this solution is unsafe! You will have to ensure that accesses to the
1219 cell are synchronized.
1223 A variable was borrowed as mutable more than once. Erroneous code example:
1225 ```compile_fail,E0499
1229 // error: cannot borrow `i` as mutable more than once at a time
1232 Please note that in rust, you can either have many immutable references, or one
1233 mutable reference. Take a look at
1234 https://doc.rust-lang.org/stable/book/references-and-borrowing.html for more
1235 information. Example:
1240 let mut x = &mut i; // ok!
1245 let b = &i; // still ok!
1246 let c = &i; // still ok!
1251 A borrowed variable was used in another closure. Example of erroneous code:
1254 fn you_know_nothing(jon_snow: &mut i32) {
1255 let nights_watch = || {
1259 *jon_snow = 3; // error: closure requires unique access to `jon_snow`
1260 // but it is already borrowed
1265 In here, `jon_snow` is already borrowed by the `nights_watch` closure, so it
1266 cannot be borrowed by the `starks` closure at the same time. To fix this issue,
1267 you can put the closure in its own scope:
1270 fn you_know_nothing(jon_snow: &mut i32) {
1272 let nights_watch = || {
1275 } // At this point, `jon_snow` is free.
1282 Or, if the type implements the `Clone` trait, you can clone it between
1286 fn you_know_nothing(jon_snow: &mut i32) {
1287 let mut jon_copy = jon_snow.clone();
1288 let nights_watch = || {
1299 This error indicates that a mutable variable is being used while it is still
1300 captured by a closure. Because the closure has borrowed the variable, it is not
1301 available for use until the closure goes out of scope.
1303 Note that a capture will either move or borrow a variable, but in this
1304 situation, the closure is borrowing the variable. Take a look at
1305 http://rustbyexample.com/fn/closures/capture.html for more information about
1308 Example of erroneous code:
1310 ```compile_fail,E0501
1311 fn inside_closure(x: &mut i32) {
1312 // Actions which require unique access
1315 fn outside_closure(x: &mut i32) {
1316 // Actions which require unique access
1319 fn foo(a: &mut i32) {
1323 outside_closure(a); // error: cannot borrow `*a` as mutable because previous
1324 // closure requires unique access.
1328 To fix this error, you can place the closure in its own scope:
1331 fn inside_closure(x: &mut i32) {}
1332 fn outside_closure(x: &mut i32) {}
1334 fn foo(a: &mut i32) {
1339 } // borrow on `a` ends.
1340 outside_closure(a); // ok!
1344 Or you can pass the variable as a parameter to the closure:
1347 fn inside_closure(x: &mut i32) {}
1348 fn outside_closure(x: &mut i32) {}
1350 fn foo(a: &mut i32) {
1351 let bar = |s: &mut i32| {
1359 It may be possible to define the closure later:
1362 fn inside_closure(x: &mut i32) {}
1363 fn outside_closure(x: &mut i32) {}
1365 fn foo(a: &mut i32) {
1375 This error indicates that you are trying to borrow a variable as mutable when it
1376 has already been borrowed as immutable.
1378 Example of erroneous code:
1380 ```compile_fail,E0502
1381 fn bar(x: &mut i32) {}
1382 fn foo(a: &mut i32) {
1383 let ref y = a; // a is borrowed as immutable.
1384 bar(a); // error: cannot borrow `*a` as mutable because `a` is also borrowed
1389 To fix this error, ensure that you don't have any other references to the
1390 variable before trying to access it mutably:
1393 fn bar(x: &mut i32) {}
1394 fn foo(a: &mut i32) {
1396 let ref y = a; // ok!
1400 For more information on the rust ownership system, take a look at
1401 https://doc.rust-lang.org/stable/book/references-and-borrowing.html.
1405 A value was used after it was mutably borrowed.
1407 Example of erroneous code:
1409 ```compile_fail,E0503
1412 // Create a mutable borrow of `value`. This borrow
1413 // lives until the end of this function.
1414 let _borrow = &mut value;
1415 let _sum = value + 1; // error: cannot use `value` because
1416 // it was mutably borrowed
1420 In this example, `value` is mutably borrowed by `borrow` and cannot be
1421 used to calculate `sum`. This is not possible because this would violate
1422 Rust's mutability rules.
1424 You can fix this error by limiting the scope of the borrow:
1429 // By creating a new block, you can limit the scope
1430 // of the reference.
1432 let _borrow = &mut value; // Use `_borrow` inside this block.
1434 // The block has ended and with it the borrow.
1435 // You can now use `value` again.
1436 let _sum = value + 1;
1440 Or by cloning `value` before borrowing it:
1445 // We clone `value`, creating a copy.
1446 let value_cloned = value.clone();
1447 // The mutable borrow is a reference to `value` and
1448 // not to `value_cloned`...
1449 let _borrow = &mut value;
1450 // ... which means we can still use `value_cloned`,
1451 let _sum = value_cloned + 1;
1452 // even though the borrow only ends here.
1456 You can find more information about borrowing in the rust-book:
1457 http://doc.rust-lang.org/stable/book/references-and-borrowing.html
1461 This error occurs when an attempt is made to move a borrowed variable into a
1464 Example of erroneous code:
1466 ```compile_fail,E0504
1472 let fancy_num = FancyNum { num: 5 };
1473 let fancy_ref = &fancy_num;
1476 println!("child function: {}", fancy_num.num);
1477 // error: cannot move `fancy_num` into closure because it is borrowed
1481 println!("main function: {}", fancy_ref.num);
1485 Here, `fancy_num` is borrowed by `fancy_ref` and so cannot be moved into
1486 the closure `x`. There is no way to move a value into a closure while it is
1487 borrowed, as that would invalidate the borrow.
1489 If the closure can't outlive the value being moved, try using a reference
1498 let fancy_num = FancyNum { num: 5 };
1499 let fancy_ref = &fancy_num;
1502 // fancy_ref is usable here because it doesn't move `fancy_num`
1503 println!("child function: {}", fancy_ref.num);
1508 println!("main function: {}", fancy_num.num);
1512 If the value has to be borrowed and then moved, try limiting the lifetime of
1513 the borrow using a scoped block:
1521 let fancy_num = FancyNum { num: 5 };
1524 let fancy_ref = &fancy_num;
1525 println!("main function: {}", fancy_ref.num);
1526 // `fancy_ref` goes out of scope here
1530 // `fancy_num` can be moved now (no more references exist)
1531 println!("child function: {}", fancy_num.num);
1538 If the lifetime of a reference isn't enough, such as in the case of threading,
1539 consider using an `Arc` to create a reference-counted value:
1550 let fancy_ref1 = Arc::new(FancyNum { num: 5 });
1551 let fancy_ref2 = fancy_ref1.clone();
1553 let x = thread::spawn(move || {
1554 // `fancy_ref1` can be moved and has a `'static` lifetime
1555 println!("child thread: {}", fancy_ref1.num);
1558 x.join().expect("child thread should finish");
1559 println!("main thread: {}", fancy_ref2.num);
1565 A value was moved out while it was still borrowed.
1567 Erroneous code example:
1569 ```compile_fail,E0505
1572 fn eat(val: Value) {}
1577 let _ref_to_val: &Value = &x;
1583 Here, the function `eat` takes the ownership of `x`. However,
1584 `x` cannot be moved because it was borrowed to `_ref_to_val`.
1585 To fix that you can do few different things:
1587 * Try to avoid moving the variable.
1588 * Release borrow before move.
1589 * Implement the `Copy` trait on the type.
1596 fn eat(val: &Value) {}
1601 let _ref_to_val: &Value = &x;
1602 eat(&x); // pass by reference, if it's possible
1612 fn eat(val: Value) {}
1617 let _ref_to_val: &Value = &x;
1619 eat(x); // release borrow and then move it.
1626 #[derive(Clone, Copy)] // implement Copy trait
1629 fn eat(val: Value) {}
1634 let _ref_to_val: &Value = &x;
1635 eat(x); // it will be copied here.
1640 You can find more information about borrowing in the rust-book:
1641 http://doc.rust-lang.org/stable/book/references-and-borrowing.html
1645 This error occurs when an attempt is made to assign to a borrowed value.
1647 Example of erroneous code:
1649 ```compile_fail,E0506
1655 let mut fancy_num = FancyNum { num: 5 };
1656 let fancy_ref = &fancy_num;
1657 fancy_num = FancyNum { num: 6 };
1658 // error: cannot assign to `fancy_num` because it is borrowed
1660 println!("Num: {}, Ref: {}", fancy_num.num, fancy_ref.num);
1664 Because `fancy_ref` still holds a reference to `fancy_num`, `fancy_num` can't
1665 be assigned to a new value as it would invalidate the reference.
1667 Alternatively, we can move out of `fancy_num` into a second `fancy_num`:
1675 let mut fancy_num = FancyNum { num: 5 };
1676 let moved_num = fancy_num;
1677 fancy_num = FancyNum { num: 6 };
1679 println!("Num: {}, Moved num: {}", fancy_num.num, moved_num.num);
1683 If the value has to be borrowed, try limiting the lifetime of the borrow using
1692 let mut fancy_num = FancyNum { num: 5 };
1695 let fancy_ref = &fancy_num;
1696 println!("Ref: {}", fancy_ref.num);
1699 // Works because `fancy_ref` is no longer in scope
1700 fancy_num = FancyNum { num: 6 };
1701 println!("Num: {}", fancy_num.num);
1705 Or by moving the reference into a function:
1713 let mut fancy_num = FancyNum { num: 5 };
1715 print_fancy_ref(&fancy_num);
1717 // Works because function borrow has ended
1718 fancy_num = FancyNum { num: 6 };
1719 println!("Num: {}", fancy_num.num);
1722 fn print_fancy_ref(fancy_ref: &FancyNum){
1723 println!("Ref: {}", fancy_ref.num);
1729 You tried to move out of a value which was borrowed. Erroneous code example:
1731 ```compile_fail,E0507
1732 use std::cell::RefCell;
1734 struct TheDarkKnight;
1736 impl TheDarkKnight {
1737 fn nothing_is_true(self) {}
1741 let x = RefCell::new(TheDarkKnight);
1743 x.borrow().nothing_is_true(); // error: cannot move out of borrowed content
1747 Here, the `nothing_is_true` method takes the ownership of `self`. However,
1748 `self` cannot be moved because `.borrow()` only provides an `&TheDarkKnight`,
1749 which is a borrow of the content owned by the `RefCell`. To fix this error,
1750 you have three choices:
1752 * Try to avoid moving the variable.
1753 * Somehow reclaim the ownership.
1754 * Implement the `Copy` trait on the type.
1759 use std::cell::RefCell;
1761 struct TheDarkKnight;
1763 impl TheDarkKnight {
1764 fn nothing_is_true(&self) {} // First case, we don't take ownership
1768 let x = RefCell::new(TheDarkKnight);
1770 x.borrow().nothing_is_true(); // ok!
1777 use std::cell::RefCell;
1779 struct TheDarkKnight;
1781 impl TheDarkKnight {
1782 fn nothing_is_true(self) {}
1786 let x = RefCell::new(TheDarkKnight);
1787 let x = x.into_inner(); // we get back ownership
1789 x.nothing_is_true(); // ok!
1796 use std::cell::RefCell;
1798 #[derive(Clone, Copy)] // we implement the Copy trait
1799 struct TheDarkKnight;
1801 impl TheDarkKnight {
1802 fn nothing_is_true(self) {}
1806 let x = RefCell::new(TheDarkKnight);
1808 x.borrow().nothing_is_true(); // ok!
1812 Moving a member out of a mutably borrowed struct will also cause E0507 error:
1814 ```compile_fail,E0507
1815 struct TheDarkKnight;
1817 impl TheDarkKnight {
1818 fn nothing_is_true(self) {}
1822 knight: TheDarkKnight
1826 let mut cave = Batcave {
1827 knight: TheDarkKnight
1829 let borrowed = &mut cave;
1831 borrowed.knight.nothing_is_true(); // E0507
1835 It is fine only if you put something back. `mem::replace` can be used for that:
1838 # struct TheDarkKnight;
1839 # impl TheDarkKnight { fn nothing_is_true(self) {} }
1840 # struct Batcave { knight: TheDarkKnight }
1843 let mut cave = Batcave {
1844 knight: TheDarkKnight
1846 let borrowed = &mut cave;
1848 mem::replace(&mut borrowed.knight, TheDarkKnight).nothing_is_true(); // ok!
1851 You can find more information about borrowing in the rust-book:
1852 http://doc.rust-lang.org/book/first-edition/references-and-borrowing.html
1856 A value was moved out of a non-copy fixed-size array.
1858 Example of erroneous code:
1860 ```compile_fail,E0508
1864 let array = [NonCopy; 1];
1865 let _value = array[0]; // error: cannot move out of type `[NonCopy; 1]`,
1866 // a non-copy fixed-size array
1870 The first element was moved out of the array, but this is not
1871 possible because `NonCopy` does not implement the `Copy` trait.
1873 Consider borrowing the element instead of moving it:
1879 let array = [NonCopy; 1];
1880 let _value = &array[0]; // Borrowing is allowed, unlike moving.
1884 Alternatively, if your type implements `Clone` and you need to own the value,
1885 consider borrowing and then cloning:
1892 let array = [NonCopy; 1];
1893 // Now you can clone the array element.
1894 let _value = array[0].clone();
1900 This error occurs when an attempt is made to move out of a value whose type
1901 implements the `Drop` trait.
1903 Example of erroneous code:
1905 ```compile_fail,E0509
1914 impl Drop for DropStruct {
1915 fn drop(&mut self) {
1916 // Destruct DropStruct, possibly using FancyNum
1921 let drop_struct = DropStruct{fancy: FancyNum{num: 5}};
1922 let fancy_field = drop_struct.fancy; // Error E0509
1923 println!("Fancy: {}", fancy_field.num);
1924 // implicit call to `drop_struct.drop()` as drop_struct goes out of scope
1928 Here, we tried to move a field out of a struct of type `DropStruct` which
1929 implements the `Drop` trait. However, a struct cannot be dropped if one or
1930 more of its fields have been moved.
1932 Structs implementing the `Drop` trait have an implicit destructor that gets
1933 called when they go out of scope. This destructor may use the fields of the
1934 struct, so moving out of the struct could make it impossible to run the
1935 destructor. Therefore, we must think of all values whose type implements the
1936 `Drop` trait as single units whose fields cannot be moved.
1938 This error can be fixed by creating a reference to the fields of a struct,
1939 enum, or tuple using the `ref` keyword:
1950 impl Drop for DropStruct {
1951 fn drop(&mut self) {
1952 // Destruct DropStruct, possibly using FancyNum
1957 let drop_struct = DropStruct{fancy: FancyNum{num: 5}};
1958 let ref fancy_field = drop_struct.fancy; // No more errors!
1959 println!("Fancy: {}", fancy_field.num);
1960 // implicit call to `drop_struct.drop()` as drop_struct goes out of scope
1964 Note that this technique can also be used in the arms of a match expression:
1975 impl Drop for DropEnum {
1976 fn drop(&mut self) {
1977 // Destruct DropEnum, possibly using FancyNum
1982 // Creates and enum of type `DropEnum`, which implements `Drop`
1983 let drop_enum = DropEnum::Fancy(FancyNum{num: 10});
1985 // Creates a reference to the inside of `DropEnum::Fancy`
1986 DropEnum::Fancy(ref fancy_field) => // No error!
1987 println!("It was fancy-- {}!", fancy_field.num),
1989 // implicit call to `drop_enum.drop()` as drop_enum goes out of scope
1995 Cannot mutate place in this match guard.
1997 When matching on a variable it cannot be mutated in the match guards, as this
1998 could cause the match to be non-exhaustive:
2000 ```compile_fail,E0510
2001 #![feature(nll, bind_by_move_pattern_guards)]
2002 let mut x = Some(0);
2005 Some(v) if { x = None; false } => (),
2006 Some(_) => (), // No longer matches
2010 Here executing `x = None` would modify the value being matched and require us
2011 to go "back in time" to the `None` arm.
2015 When matching against an exclusive range, the compiler verifies that the range
2016 is non-empty. Exclusive range patterns include the start point but not the end
2017 point, so this is equivalent to requiring the start of the range to be less
2018 than the end of the range.
2024 // This range is ok, albeit pointless.
2026 // This range is empty, and the compiler can tell.
2033 Closures cannot mutate immutable captured variables.
2035 Erroneous code example:
2037 ```compile_fail,E0595
2038 let x = 3; // error: closure cannot assign to immutable local variable `x`
2039 let mut c = || { x += 1 };
2042 Make the variable binding mutable:
2045 let mut x = 3; // ok!
2046 let mut c = || { x += 1 };
2051 This error occurs because you tried to mutably borrow a non-mutable variable.
2053 Example of erroneous code:
2055 ```compile_fail,E0596
2057 let y = &mut x; // error: cannot borrow mutably
2060 In here, `x` isn't mutable, so when we try to mutably borrow it in `y`, it
2061 fails. To fix this error, you need to make `x` mutable:
2065 let y = &mut x; // ok!
2070 This error occurs because a borrow was made inside a variable which has a
2071 greater lifetime than the borrowed one.
2073 Example of erroneous code:
2075 ```compile_fail,E0597
2080 let mut x = Foo { x: None };
2082 x.x = Some(&y); // error: `y` does not live long enough
2085 In here, `x` is created before `y` and therefore has a greater lifetime. Always
2086 keep in mind that values in a scope are dropped in the opposite order they are
2087 created. So to fix the previous example, just make the `y` lifetime greater than
2096 let mut x = Foo { x: None };
2102 This error occurs because a borrow in a generator persists across a
2105 ```compile_fail,E0626
2106 # #![feature(generators, generator_trait)]
2107 # use std::ops::Generator;
2109 let a = &String::new(); // <-- This borrow...
2110 yield (); // ...is still in scope here, when the yield occurs.
2113 unsafe { b.resume() };
2116 At present, it is not permitted to have a yield that occurs while a
2117 borrow is still in scope. To resolve this error, the borrow must
2118 either be "contained" to a smaller scope that does not overlap the
2119 yield or else eliminated in another way. So, for example, we might
2120 resolve the previous example by removing the borrow and just storing
2121 the integer by value:
2124 # #![feature(generators, generator_trait)]
2125 # use std::ops::Generator;
2131 unsafe { b.resume() };
2134 This is a very simple case, of course. In more complex cases, we may
2135 wish to have more than one reference to the value that was borrowed --
2136 in those cases, something like the `Rc` or `Arc` types may be useful.
2138 This error also frequently arises with iteration:
2140 ```compile_fail,E0626
2141 # #![feature(generators, generator_trait)]
2142 # use std::ops::Generator;
2144 let v = vec![1,2,3];
2145 for &x in &v { // <-- borrow of `v` is still in scope...
2146 yield x; // ...when this yield occurs.
2149 unsafe { b.resume() };
2152 Such cases can sometimes be resolved by iterating "by value" (or using
2153 `into_iter()`) to avoid borrowing:
2156 # #![feature(generators, generator_trait)]
2157 # use std::ops::Generator;
2159 let v = vec![1,2,3];
2160 for x in v { // <-- Take ownership of the values instead!
2161 yield x; // <-- Now yield is OK.
2164 unsafe { b.resume() };
2167 If taking ownership is not an option, using indices can work too:
2170 # #![feature(generators, generator_trait)]
2171 # use std::ops::Generator;
2173 let v = vec![1,2,3];
2174 let len = v.len(); // (*)
2176 let x = v[i]; // (*)
2177 yield x; // <-- Now yield is OK.
2180 unsafe { b.resume() };
2182 // (*) -- Unfortunately, these temporaries are currently required.
2183 // See <https://github.com/rust-lang/rust/issues/43122>.
2188 This error occurs because a borrow of a thread-local variable was made inside a
2189 function which outlived the lifetime of the function.
2191 Example of erroneous code:
2193 ```compile_fail,E0712
2195 #![feature(thread_local)]
2201 let a = &FOO; // error: thread-local variable borrowed past end of function
2203 std::thread::spawn(move || {
2211 This error occurs when an attempt is made to borrow state past the end of the
2212 lifetime of a type that implements the `Drop` trait.
2214 Example of erroneous code:
2216 ```compile_fail,E0713
2219 pub struct S<'a> { data: &'a mut String }
2221 impl<'a> Drop for S<'a> {
2222 fn drop(&mut self) { self.data.push_str("being dropped"); }
2225 fn demo<'a>(s: S<'a>) -> &'a mut String { let p = &mut *s.data; p }
2228 Here, `demo` tries to borrow the string data held within its
2229 argument `s` and then return that borrow. However, `S` is
2230 declared as implementing `Drop`.
2232 Structs implementing the `Drop` trait have an implicit destructor that
2233 gets called when they go out of scope. This destructor gets exclusive
2234 access to the fields of the struct when it runs.
2236 This means that when `s` reaches the end of `demo`, its destructor
2237 gets exclusive access to its `&mut`-borrowed string data. allowing
2238 another borrow of that string data (`p`), to exist across the drop of
2239 `s` would be a violation of the principle that `&mut`-borrows have
2240 exclusive, unaliased access to their referenced data.
2242 This error can be fixed by changing `demo` so that the destructor does
2243 not run while the string-data is borrowed; for example by taking `S`
2249 pub struct S<'a> { data: &'a mut String }
2251 impl<'a> Drop for S<'a> {
2252 fn drop(&mut self) { self.data.push_str("being dropped"); }
2255 fn demo<'a>(s: &'a mut S<'a>) -> &'a mut String { let p = &mut *(*s).data; p }
2258 Note that this approach needs a reference to S with lifetime `'a`.
2259 Nothing shorter than `'a` will suffice: a shorter lifetime would imply
2260 that after `demo` finishes excuting, something else (such as the
2261 destructor!) could access `s.data` after the end of that shorter
2262 lifetime, which would again violate the `&mut`-borrow's exclusive
2269 register_diagnostics! {
2270 // E0298, // cannot compare constants
2271 // E0299, // mismatched types between arms
2272 // E0471, // constant evaluation error (in pattern)
2273 // E0385, // {} in an aliasable location
2274 E0493, // destructors cannot be evaluated at compile-time
2275 E0524, // two closures require unique access to `..` at the same time
2276 E0526, // shuffle indices are not constant
2277 E0594, // cannot assign to {}
2278 E0598, // lifetime of {} is too short to guarantee its contents can be...
2279 E0625, // thread-local statics cannot be accessed at compile-time