1 #![allow(non_snake_case)]
3 register_long_diagnostics! {
7 #### Note: this error code is no longer emitted by the compiler.
9 This error suggests that the expression arm corresponding to the noted pattern
10 will never be reached as for all possible values of the expression being
11 matched, one of the preceding patterns will match.
13 This means that perhaps some of the preceding patterns are too general, this
14 one is too specific or the ordering is incorrect.
16 For example, the following `match` block has too many arms:
20 Some(bar) => {/* ... */}
21 x => {/* ... */} // This handles the `None` case
22 _ => {/* ... */} // All possible cases have already been handled
26 `match` blocks have their patterns matched in order, so, for example, putting
27 a wildcard arm above a more specific arm will make the latter arm irrelevant.
29 Ensure the ordering of the match arm is correct and remove any superfluous
34 #### Note: this error code is no longer emitted by the compiler.
36 This error indicates that an empty match expression is invalid because the type
37 it is matching on is non-empty (there exist values of this type). In safe code
38 it is impossible to create an instance of an empty type, so empty match
39 expressions are almost never desired. This error is typically fixed by adding
40 one or more cases to the match expression.
42 An example of an empty type is `enum Empty { }`. So, the following will work:
57 fn foo(x: Option<String>) {
66 This error indicates that the compiler cannot guarantee a matching pattern for
67 one or more possible inputs to a match expression. Guaranteed matches are
68 required in order to assign values to match expressions, or alternatively,
69 determine the flow of execution. Erroneous code example:
77 let x = Terminator::HastaLaVistaBaby;
79 match x { // error: non-exhaustive patterns: `HastaLaVistaBaby` not covered
80 Terminator::TalkToMyHand => {}
84 If you encounter this error you must alter your patterns so that every possible
85 value of the input type is matched. For types with a small number of variants
86 (like enums) you should probably cover all cases explicitly. Alternatively, the
87 underscore `_` wildcard pattern can be added after all other patterns to match
88 "anything else". Example:
96 let x = Terminator::HastaLaVistaBaby;
99 Terminator::TalkToMyHand => {}
100 Terminator::HastaLaVistaBaby => {}
106 Terminator::TalkToMyHand => {}
113 Patterns used to bind names must be irrefutable, that is, they must guarantee
114 that a name will be extracted in all cases. Erroneous code example:
116 ```compile_fail,E0005
119 // error: refutable pattern in local binding: `None` not covered
122 If you encounter this error you probably need to use a `match` or `if let` to
123 deal with the possibility of failure. Example:
144 This error indicates that the bindings in a match arm would require a value to
145 be moved into more than one location, thus violating unique ownership. Code
146 like the following is invalid as it requires the entire `Option<String>` to be
147 moved into a variable called `op_string` while simultaneously requiring the
148 inner `String` to be moved into a variable called `s`.
150 ```compile_fail,E0007
151 let x = Some("s".to_string());
154 op_string @ Some(s) => {}, // error: cannot bind by-move with sub-bindings
159 See also the error E0303.
163 Names bound in match arms retain their type in pattern guards. As such, if a
164 name is bound by move in a pattern, it should also be moved to wherever it is
165 referenced in the pattern guard code. Doing so however would prevent the name
166 from being available in the body of the match arm. Consider the following:
168 ```compile_fail,E0008
169 match Some("hi".to_string()) {
170 Some(s) if s.len() == 0 => {}, // use s.
175 The variable `s` has type `String`, and its use in the guard is as a variable of
176 type `String`. The guard code effectively executes in a separate scope to the
177 body of the arm, so the value would be moved into this anonymous scope and
178 therefore becomes unavailable in the body of the arm.
180 The problem above can be solved by using the `ref` keyword.
183 match Some("hi".to_string()) {
184 Some(ref s) if s.len() == 0 => {},
189 Though this example seems innocuous and easy to solve, the problem becomes clear
190 when it encounters functions which consume the value:
192 ```compile_fail,E0008
196 fn consume(self) -> usize {
204 Some(y) if y.consume() > 0 => {}
210 In this situation, even the `ref` keyword cannot solve it, since borrowed
211 content cannot be moved. This problem cannot be solved generally. If the value
212 can be cloned, here is a not-so-specific solution:
219 fn consume(self) -> usize {
227 Some(ref y) if y.clone().consume() > 0 => {}
233 If the value will be consumed in the pattern guard, using its clone will not
234 move its ownership, so the code works.
238 In a pattern, all values that don't implement the `Copy` trait have to be bound
239 the same way. The goal here is to avoid binding simultaneously by-move and
242 This limitation may be removed in a future version of Rust.
244 Erroneous code example:
246 ```compile_fail,E0009
249 let x = Some((X { x: () }, X { x: () }));
251 Some((y, ref z)) => {}, // error: cannot bind by-move and by-ref in the
257 You have two solutions:
259 Solution #1: Bind the pattern's values the same way.
264 let x = Some((X { x: () }, X { x: () }));
266 Some((ref y, ref z)) => {},
267 // or Some((y, z)) => {}
272 Solution #2: Implement the `Copy` trait for the `X` structure.
274 However, please keep in mind that the first solution should be preferred.
277 #[derive(Clone, Copy)]
280 let x = Some((X { x: () }, X { x: () }));
282 Some((y, ref z)) => {},
289 When matching against a range, the compiler verifies that the range is
290 non-empty. Range patterns include both end-points, so this is equivalent to
291 requiring the start of the range to be less than or equal to the end of the
298 // This range is ok, albeit pointless.
300 // This range is empty, and the compiler can tell.
307 `const` and `static` mean different things. A `const` is a compile-time
308 constant, an alias for a literal value. This property means you can match it
309 directly within a pattern.
311 The `static` keyword, on the other hand, guarantees a fixed location in memory.
312 This does not always mean that the value is constant. For example, a global
313 mutex can be declared `static` as well.
315 If you want to match against a `static`, consider using a guard instead:
318 static FORTY_TWO: i32 = 42;
321 Some(x) if x == FORTY_TWO => {}
328 #### Note: this error code is no longer emitted by the compiler.
330 An if-let pattern attempts to match the pattern, and enters the body if the
331 match was successful. If the match is irrefutable (when it cannot fail to
332 match), use a regular `let`-binding instead. For instance:
335 struct Irrefutable(i32);
336 let irr = Irrefutable(0);
338 // This fails to compile because the match is irrefutable.
339 if let Irrefutable(x) = irr {
340 // This body will always be executed.
348 struct Irrefutable(i32);
349 let irr = Irrefutable(0);
351 let Irrefutable(x) = irr;
357 #### Note: this error code is no longer emitted by the compiler.
359 A while-let pattern attempts to match the pattern, and enters the body if the
360 match was successful. If the match is irrefutable (when it cannot fail to
361 match), use a regular `let`-binding inside a `loop` instead. For instance:
363 ```compile_pass,no_run
364 struct Irrefutable(i32);
365 let irr = Irrefutable(0);
367 // This fails to compile because the match is irrefutable.
368 while let Irrefutable(x) = irr {
376 struct Irrefutable(i32);
377 let irr = Irrefutable(0);
380 let Irrefutable(x) = irr;
387 Enum variants are qualified by default. For example, given this type:
396 You would match it using:
412 If you don't qualify the names, the code will bind new variables named "GET" and
413 "POST" instead. This behavior is likely not what you want, so `rustc` warns when
416 Qualified names are good practice, and most code works well with them. But if
417 you prefer them unqualified, you can import the variants into scope:
421 enum Method { GET, POST }
425 If you want others to be able to import variants from your module directly, use
430 pub enum Method { GET, POST }
437 #### Note: this error code is no longer emitted by the compiler.
439 Patterns used to bind names must be irrefutable. That is, they must guarantee
440 that a name will be extracted in all cases. Instead of pattern matching the
441 loop variable, consider using a `match` or `if let` inside the loop body. For
444 ```compile_fail,E0005
445 let xs : Vec<Option<i32>> = vec![Some(1), None];
447 // This fails because `None` is not covered.
453 Match inside the loop instead:
456 let xs : Vec<Option<i32>> = vec![Some(1), None];
469 let xs : Vec<Option<i32>> = vec![Some(1), None];
472 if let Some(x) = item {
480 Mutable borrows are not allowed in pattern guards, because matching cannot have
481 side effects. Side effects could alter the matched object or the environment
482 on which the match depends in such a way, that the match would not be
483 exhaustive. For instance, the following would not match any arm if mutable
484 borrows were allowed:
486 ```compile_fail,E0301
489 option if option.take().is_none() => {
490 /* impossible, option is `Some` */
492 Some(_) => { } // When the previous match failed, the option became `None`.
498 Assignments are not allowed in pattern guards, because matching cannot have
499 side effects. Side effects could alter the matched object or the environment
500 on which the match depends in such a way, that the match would not be
501 exhaustive. For instance, the following would not match any arm if assignments
504 ```compile_fail,E0302
507 option if { option = None; false } => { },
508 Some(_) => { } // When the previous match failed, the option became `None`.
514 In certain cases it is possible for sub-bindings to violate memory safety.
515 Updates to the borrow checker in a future version of Rust may remove this
516 restriction, but for now patterns must be rewritten without sub-bindings.
520 ```compile_fail,E0303
521 match Some("hi".to_string()) {
522 ref op_string_ref @ Some(s) => {},
530 match Some("hi".to_string()) {
532 let op_string_ref = &Some(s);
539 The `op_string_ref` binding has type `&Option<&String>` in both cases.
541 See also https://github.com/rust-lang/rust/issues/14587
545 The value of statics and constants must be known at compile time, and they live
546 for the entire lifetime of a program. Creating a boxed value allocates memory on
547 the heap at runtime, and therefore cannot be done at compile time. Erroneous
550 ```compile_fail,E0010
551 #![feature(box_syntax)]
553 const CON : Box<i32> = box 0;
558 Static and const variables can refer to other const variables. But a const
559 variable cannot refer to a static variable. For example, `Y` cannot refer to
562 ```compile_fail,E0013
567 To fix this, the value can be extracted as a const and then used:
576 // FIXME(#57563) Change the language here when const fn stabilizes
578 The only functions that can be called in static or constant expressions are
579 `const` functions, and struct/enum constructors. `const` functions are only
580 available on a nightly compiler. Rust currently does not support more general
581 compile-time function execution.
584 const FOO: Option<u8> = Some(1); // enum constructor
586 const BAR: Bar = Bar {x: 1}; // struct constructor
589 See [RFC 911] for more details on the design of `const fn`s.
591 [RFC 911]: https://github.com/rust-lang/rfcs/blob/master/text/0911-const-fn.md
595 References in statics and constants may only refer to immutable values.
596 Erroneous code example:
598 ```compile_fail,E0017
602 // these three are not allowed:
603 const CR: &mut i32 = &mut C;
604 static STATIC_REF: &'static mut i32 = &mut X;
605 static CONST_REF: &'static mut i32 = &mut C;
608 Statics are shared everywhere, and if they refer to mutable data one might
609 violate memory safety since holding multiple mutable references to shared data
612 If you really want global mutable state, try using `static mut` or a global
617 A function call isn't allowed in the const's initialization expression
618 because the expression's value must be known at compile-time. Erroneous code
627 fn test(&self) -> i32 {
633 const FOO: Test = Test::V1;
635 const A: i32 = FOO.test(); // You can't call Test::func() here!
639 Remember: you can't use a function call inside a const's initialization
640 expression! However, you can totally use it anywhere else:
648 fn func(&self) -> i32 {
654 const FOO: Test = Test::V1;
656 FOO.func(); // here is good
657 let x = FOO.func(); // or even here!
663 Unsafe code was used outside of an unsafe function or block.
665 Erroneous code example:
667 ```compile_fail,E0133
668 unsafe fn f() { return; } // This is the unsafe code
671 f(); // error: call to unsafe function requires unsafe function or block
675 Using unsafe functionality is potentially dangerous and disallowed by safety
678 * Dereferencing raw pointers
679 * Calling functions via FFI
680 * Calling functions marked unsafe
682 These safety checks can be relaxed for a section of the code by wrapping the
683 unsafe instructions with an `unsafe` block. For instance:
686 unsafe fn f() { return; }
689 unsafe { f(); } // ok!
693 See also https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html
697 This error occurs when an attempt is made to use data captured by a closure,
698 when that data may no longer exist. It's most commonly seen when attempting to
701 ```compile_fail,E0373
702 fn foo() -> Box<Fn(u32) -> u32> {
708 Notice that `x` is stack-allocated by `foo()`. By default, Rust captures
709 closed-over data by reference. This means that once `foo()` returns, `x` no
710 longer exists. An attempt to access `x` within the closure would thus be
713 Another situation where this might be encountered is when spawning threads:
715 ```compile_fail,E0373
720 let thr = std::thread::spawn(|| {
726 Since our new thread runs in parallel, the stack frame containing `x` and `y`
727 may well have disappeared by the time we try to use them. Even if we call
728 `thr.join()` within foo (which blocks until `thr` has completed, ensuring the
729 stack frame won't disappear), we will not succeed: the compiler cannot prove
730 that this behaviour is safe, and so won't let us do it.
732 The solution to this problem is usually to switch to using a `move` closure.
733 This approach moves (or copies, where possible) data into the closure, rather
734 than taking references to it. For example:
737 fn foo() -> Box<Fn(u32) -> u32> {
739 Box::new(move |y| x + y)
743 Now that the closure has its own copy of the data, there's no need to worry
748 It is not allowed to use or capture an uninitialized variable. For example:
750 ```compile_fail,E0381
753 let y = x; // error, use of possibly uninitialized variable
757 To fix this, ensure that any declared variables are initialized before being
769 This error occurs when an attempt is made to use a variable after its contents
770 have been moved elsewhere. For example:
772 ```compile_fail,E0382
773 struct MyStruct { s: u32 }
776 let mut x = MyStruct{ s: 5u32 };
783 Since `MyStruct` is a type that is not marked `Copy`, the data gets moved out
784 of `x` when we set `y`. This is fundamental to Rust's ownership system: outside
785 of workarounds like `Rc`, a value cannot be owned by more than one variable.
787 Sometimes we don't need to move the value. Using a reference, we can let another
788 function borrow the value without changing its ownership. In the example below,
789 we don't actually have to move our string to `calculate_length`, we can give it
790 a reference to it with `&` instead.
794 let s1 = String::from("hello");
796 let len = calculate_length(&s1);
798 println!("The length of '{}' is {}.", s1, len);
801 fn calculate_length(s: &String) -> usize {
806 A mutable reference can be created with `&mut`.
808 Sometimes we don't want a reference, but a duplicate. All types marked `Clone`
809 can be duplicated by calling `.clone()`. Subsequent changes to a clone do not
810 affect the original variable.
812 Most types in the standard library are marked `Clone`. The example below
813 demonstrates using `clone()` on a string. `s1` is first set to "many", and then
814 copied to `s2`. Then the first character of `s1` is removed, without affecting
815 `s2`. "any many" is printed to the console.
819 let mut s1 = String::from("many");
822 println!("{} {}", s1, s2);
826 If we control the definition of a type, we can implement `Clone` on it ourselves
827 with `#[derive(Clone)]`.
829 Some types have no ownership semantics at all and are trivial to duplicate. An
830 example is `i32` and the other number types. We don't have to call `.clone()` to
831 clone them, because they are marked `Copy` in addition to `Clone`. Implicit
832 cloning is more convenient in this case. We can mark our own types `Copy` if
833 all their members also are marked `Copy`.
835 In the example below, we implement a `Point` type. Because it only stores two
836 integers, we opt-out of ownership semantics with `Copy`. Then we can
837 `let p2 = p1` without `p1` being moved.
840 #[derive(Copy, Clone)]
841 struct Point { x: i32, y: i32 }
844 let mut p1 = Point{ x: -1, y: 2 };
847 println!("p1: {}, {}", p1.x, p1.y);
848 println!("p2: {}, {}", p2.x, p2.y);
852 Alternatively, if we don't control the struct's definition, or mutable shared
853 ownership is truly required, we can use `Rc` and `RefCell`:
856 use std::cell::RefCell;
859 struct MyStruct { s: u32 }
862 let mut x = Rc::new(RefCell::new(MyStruct{ s: 5u32 }));
864 x.borrow_mut().s = 6;
865 println!("{}", x.borrow().s);
869 With this approach, x and y share ownership of the data via the `Rc` (reference
870 count type). `RefCell` essentially performs runtime borrow checking: ensuring
871 that at most one writer or multiple readers can access the data at any one time.
873 If you wish to learn more about ownership in Rust, start with the chapter in the
876 https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html
880 #### Note: this error code is no longer emitted by the compiler.
882 This error occurs when an attempt is made to partially reinitialize a
883 structure that is currently uninitialized.
885 For example, this can happen when a drop has taken place:
892 fn drop(&mut self) { /* ... */ }
895 let mut x = Foo { a: 1 };
896 drop(x); // `x` is now uninitialized
897 x.a = 2; // error, partial reinitialization of uninitialized structure `t`
900 This error can be fixed by fully reinitializing the structure in question:
907 fn drop(&mut self) { /* ... */ }
910 let mut x = Foo { a: 1 };
917 This error occurs when an attempt is made to reassign an immutable variable.
920 ```compile_fail,E0384
923 x = 5; // error, reassignment of immutable variable
927 By default, variables in Rust are immutable. To fix this error, add the keyword
928 `mut` after the keyword `let` when declaring the variable. For example:
939 This error occurs when an attempt is made to mutate the target of a mutable
940 reference stored inside an immutable container.
942 For example, this can happen when storing a `&mut` inside an immutable `Box`:
944 ```compile_fail,E0386
946 let y: Box<_> = Box::new(&mut x);
947 **y = 2; // error, cannot assign to data in an immutable container
950 This error can be fixed by making the container mutable:
954 let mut y: Box<_> = Box::new(&mut x);
958 It can also be fixed by using a type with interior mutability, such as `Cell`
965 let y: Box<Cell<_>> = Box::new(Cell::new(x));
971 #### Note: this error code is no longer emitted by the compiler.
973 This error occurs when an attempt is made to mutate or mutably reference data
974 that a closure has captured immutably. Examples of this error are shown below:
977 // Accepts a function or a closure that captures its environment immutably.
978 // Closures passed to foo will not be able to mutate their closed-over state.
979 fn foo<F: Fn()>(f: F) { }
981 // Attempts to mutate closed-over data. Error message reads:
982 // `cannot assign to data in a captured outer variable...`
988 // Attempts to take a mutable reference to closed-over data. Error message
989 // reads: `cannot borrow data mutably in a captured outer variable...`
992 foo(|| { let y = &mut x; });
996 The problem here is that foo is defined as accepting a parameter of type `Fn`.
997 Closures passed into foo will thus be inferred to be of type `Fn`, meaning that
998 they capture their context immutably.
1000 If the definition of `foo` is under your control, the simplest solution is to
1001 capture the data mutably. This can be done by defining `foo` to take FnMut
1005 fn foo<F: FnMut()>(f: F) { }
1008 Alternatively, we can consider using the `Cell` and `RefCell` types to achieve
1009 interior mutability through a shared reference. Our example's `mutable`
1010 function could be redefined as below:
1013 use std::cell::Cell;
1015 fn foo<F: Fn()>(f: F) { }
1018 let x = Cell::new(0u32);
1023 You can read more about cell types in the API documentation:
1025 https://doc.rust-lang.org/std/cell/
1029 E0388 was removed and is no longer issued.
1033 #### Note: this error code is no longer emitted by the compiler.
1035 An attempt was made to mutate data using a non-mutable reference. This
1036 commonly occurs when attempting to assign to a non-mutable reference of a
1037 mutable reference (`&(&mut T)`).
1039 Example of erroneous code:
1047 let mut fancy = FancyNum{ num: 5 };
1048 let fancy_ref = &(&mut fancy);
1049 fancy_ref.num = 6; // error: cannot assign to data in a `&` reference
1050 println!("{}", fancy_ref.num);
1054 Here, `&mut fancy` is mutable, but `&(&mut fancy)` is not. Creating an
1055 immutable reference to a value borrows it immutably. There can be multiple
1056 references of type `&(&mut T)` that point to the same value, so they must be
1057 immutable to prevent multiple mutable references to the same value.
1059 To fix this, either remove the outer reference:
1067 let mut fancy = FancyNum{ num: 5 };
1069 let fancy_ref = &mut fancy;
1070 // `fancy_ref` is now &mut FancyNum, rather than &(&mut FancyNum)
1072 fancy_ref.num = 6; // No error!
1074 println!("{}", fancy_ref.num);
1078 Or make the outer reference mutable:
1086 let mut fancy = FancyNum{ num: 5 };
1088 let fancy_ref = &mut (&mut fancy);
1089 // `fancy_ref` is now &mut(&mut FancyNum), rather than &(&mut FancyNum)
1091 fancy_ref.num = 6; // No error!
1093 println!("{}", fancy_ref.num);
1099 A value was moved. However, its size was not known at compile time, and only
1100 values of a known size can be moved.
1102 Erroneous code example:
1105 #![feature(box_syntax)]
1108 let array: &[isize] = &[1, 2, 3];
1109 let _x: Box<[isize]> = box *array;
1110 // error: cannot move a value of type [isize]: the size of [isize] cannot
1111 // be statically determined
1115 In Rust, you can only move a value when its size is known at compile time.
1117 To work around this restriction, consider "hiding" the value behind a reference:
1118 either `&x` or `&mut x`. Since a reference has a fixed size, this lets you move
1119 it around as usual. Example:
1122 #![feature(box_syntax)]
1125 let array: &[isize] = &[1, 2, 3];
1126 let _x: Box<&[isize]> = box array; // ok!
1132 A borrow of a constant containing interior mutability was attempted. Erroneous
1135 ```compile_fail,E0492
1136 use std::sync::atomic::AtomicUsize;
1138 const A: AtomicUsize = AtomicUsize::new(0);
1139 static B: &'static AtomicUsize = &A;
1140 // error: cannot borrow a constant which may contain interior mutability,
1141 // create a static instead
1144 A `const` represents a constant value that should never change. If one takes
1145 a `&` reference to the constant, then one is taking a pointer to some memory
1146 location containing the value. Normally this is perfectly fine: most values
1147 can't be changed via a shared `&` pointer, but interior mutability would allow
1148 it. That is, a constant value could be mutated. On the other hand, a `static` is
1149 explicitly a single memory location, which can be mutated at will.
1151 So, in order to solve this error, either use statics which are `Sync`:
1154 use std::sync::atomic::AtomicUsize;
1156 static A: AtomicUsize = AtomicUsize::new(0);
1157 static B: &'static AtomicUsize = &A; // ok!
1160 You can also have this error while using a cell type:
1162 ```compile_fail,E0492
1163 use std::cell::Cell;
1165 const A: Cell<usize> = Cell::new(1);
1166 const B: &Cell<usize> = &A;
1167 // error: cannot borrow a constant which may contain interior mutability,
1168 // create a static instead
1171 struct C { a: Cell<usize> }
1173 const D: C = C { a: Cell::new(1) };
1174 const E: &Cell<usize> = &D.a; // error
1177 const F: &C = &D; // error
1180 This is because cell types do operations that are not thread-safe. Due to this,
1181 they don't implement Sync and thus can't be placed in statics.
1183 However, if you still wish to use these types, you can achieve this by an unsafe
1187 use std::cell::Cell;
1188 use std::marker::Sync;
1190 struct NotThreadSafe<T> {
1194 unsafe impl<T> Sync for NotThreadSafe<T> {}
1196 static A: NotThreadSafe<usize> = NotThreadSafe { value : Cell::new(1) };
1197 static B: &'static NotThreadSafe<usize> = &A; // ok!
1200 Remember this solution is unsafe! You will have to ensure that accesses to the
1201 cell are synchronized.
1205 A variable was borrowed as mutable more than once. Erroneous code example:
1207 ```compile_fail,E0499
1212 // error: cannot borrow `i` as mutable more than once at a time
1215 Please note that in rust, you can either have many immutable references, or one
1216 mutable reference. Take a look at
1217 https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html for more
1218 information. Example:
1223 let mut x = &mut i; // ok!
1228 let b = &i; // still ok!
1229 let c = &i; // still ok!
1236 A borrowed variable was used by a closure. Example of erroneous code:
1238 ```compile_fail,E0500
1239 fn you_know_nothing(jon_snow: &mut i32) {
1240 let nights_watch = &jon_snow;
1242 *jon_snow = 3; // error: closure requires unique access to `jon_snow`
1243 // but it is already borrowed
1245 println!("{}", nights_watch);
1249 In here, `jon_snow` is already borrowed by the `nights_watch` reference, so it
1250 cannot be borrowed by the `starks` closure at the same time. To fix this issue,
1251 you can create the closure after the borrow has ended:
1254 fn you_know_nothing(jon_snow: &mut i32) {
1255 let nights_watch = &jon_snow;
1256 println!("{}", nights_watch);
1263 Or, if the type implements the `Clone` trait, you can clone it between
1267 fn you_know_nothing(jon_snow: &mut i32) {
1268 let mut jon_copy = jon_snow.clone();
1272 println!("{}", jon_copy);
1278 This error indicates that a mutable variable is being used while it is still
1279 captured by a closure. Because the closure has borrowed the variable, it is not
1280 available for use until the closure goes out of scope.
1282 Note that a capture will either move or borrow a variable, but in this
1283 situation, the closure is borrowing the variable. Take a look at
1284 http://rustbyexample.com/fn/closures/capture.html for more information about
1287 Example of erroneous code:
1289 ```compile_fail,E0501
1290 fn inside_closure(x: &mut i32) {
1291 // Actions which require unique access
1294 fn outside_closure(x: &mut i32) {
1295 // Actions which require unique access
1298 fn foo(a: &mut i32) {
1302 outside_closure(a); // error: cannot borrow `*a` as mutable because previous
1303 // closure requires unique access.
1308 To fix this error, you can finish using the closure before using the captured
1312 fn inside_closure(x: &mut i32) {}
1313 fn outside_closure(x: &mut i32) {}
1315 fn foo(a: &mut i32) {
1320 // borrow on `a` ends.
1321 outside_closure(a); // ok!
1325 Or you can pass the variable as a parameter to the closure:
1328 fn inside_closure(x: &mut i32) {}
1329 fn outside_closure(x: &mut i32) {}
1331 fn foo(a: &mut i32) {
1332 let mut bar = |s: &mut i32| {
1340 It may be possible to define the closure later:
1343 fn inside_closure(x: &mut i32) {}
1344 fn outside_closure(x: &mut i32) {}
1346 fn foo(a: &mut i32) {
1357 This error indicates that you are trying to borrow a variable as mutable when it
1358 has already been borrowed as immutable.
1360 Example of erroneous code:
1362 ```compile_fail,E0502
1363 fn bar(x: &mut i32) {}
1364 fn foo(a: &mut i32) {
1365 let ref y = a; // a is borrowed as immutable.
1366 bar(a); // error: cannot borrow `*a` as mutable because `a` is also borrowed
1372 To fix this error, ensure that you don't have any other references to the
1373 variable before trying to access it mutably:
1376 fn bar(x: &mut i32) {}
1377 fn foo(a: &mut i32) {
1379 let ref y = a; // ok!
1384 For more information on the rust ownership system, take a look at
1385 https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html.
1389 A value was used after it was mutably borrowed.
1391 Example of erroneous code:
1393 ```compile_fail,E0503
1396 // Create a mutable borrow of `value`.
1397 let borrow = &mut value;
1398 let _sum = value + 1; // error: cannot use `value` because
1399 // it was mutably borrowed
1400 println!("{}", borrow);
1404 In this example, `value` is mutably borrowed by `borrow` and cannot be
1405 used to calculate `sum`. This is not possible because this would violate
1406 Rust's mutability rules.
1408 You can fix this error by finishing using the borrow before the next use of
1414 let borrow = &mut value;
1415 println!("{}", borrow);
1416 // The block has ended and with it the borrow.
1417 // You can now use `value` again.
1418 let _sum = value + 1;
1422 Or by cloning `value` before borrowing it:
1427 // We clone `value`, creating a copy.
1428 let value_cloned = value.clone();
1429 // The mutable borrow is a reference to `value` and
1430 // not to `value_cloned`...
1431 let borrow = &mut value;
1432 // ... which means we can still use `value_cloned`,
1433 let _sum = value_cloned + 1;
1434 // even though the borrow only ends here.
1435 println!("{}", borrow);
1439 You can find more information about borrowing in the rust-book:
1440 http://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html
1444 #### Note: this error code is no longer emitted by the compiler.
1446 This error occurs when an attempt is made to move a borrowed variable into a
1449 Example of erroneous code:
1457 let fancy_num = FancyNum { num: 5 };
1458 let fancy_ref = &fancy_num;
1461 println!("child function: {}", fancy_num.num);
1462 // error: cannot move `fancy_num` into closure because it is borrowed
1466 println!("main function: {}", fancy_ref.num);
1470 Here, `fancy_num` is borrowed by `fancy_ref` and so cannot be moved into
1471 the closure `x`. There is no way to move a value into a closure while it is
1472 borrowed, as that would invalidate the borrow.
1474 If the closure can't outlive the value being moved, try using a reference
1483 let fancy_num = FancyNum { num: 5 };
1484 let fancy_ref = &fancy_num;
1487 // fancy_ref is usable here because it doesn't move `fancy_num`
1488 println!("child function: {}", fancy_ref.num);
1493 println!("main function: {}", fancy_num.num);
1497 If the value has to be borrowed and then moved, try limiting the lifetime of
1498 the borrow using a scoped block:
1506 let fancy_num = FancyNum { num: 5 };
1509 let fancy_ref = &fancy_num;
1510 println!("main function: {}", fancy_ref.num);
1511 // `fancy_ref` goes out of scope here
1515 // `fancy_num` can be moved now (no more references exist)
1516 println!("child function: {}", fancy_num.num);
1523 If the lifetime of a reference isn't enough, such as in the case of threading,
1524 consider using an `Arc` to create a reference-counted value:
1535 let fancy_ref1 = Arc::new(FancyNum { num: 5 });
1536 let fancy_ref2 = fancy_ref1.clone();
1538 let x = thread::spawn(move || {
1539 // `fancy_ref1` can be moved and has a `'static` lifetime
1540 println!("child thread: {}", fancy_ref1.num);
1543 x.join().expect("child thread should finish");
1544 println!("main thread: {}", fancy_ref2.num);
1550 A value was moved out while it was still borrowed.
1552 Erroneous code example:
1554 ```compile_fail,E0505
1557 fn borrow(val: &Value) {}
1559 fn eat(val: Value) {}
1563 let _ref_to_val: &Value = &x;
1565 borrow(_ref_to_val);
1569 Here, the function `eat` takes ownership of `x`. However,
1570 `x` cannot be moved because the borrow to `_ref_to_val`
1571 needs to last till the function `borrow`.
1572 To fix that you can do a few different things:
1574 * Try to avoid moving the variable.
1575 * Release borrow before move.
1576 * Implement the `Copy` trait on the type.
1583 fn borrow(val: &Value) {}
1585 fn eat(val: &Value) {}
1590 let ref_to_val: &Value = &x;
1591 eat(&x); // pass by reference, if it's possible
1601 fn borrow(val: &Value) {}
1603 fn eat(val: Value) {}
1608 let ref_to_val: &Value = &x;
1610 // ref_to_val is no longer used.
1618 #[derive(Clone, Copy)] // implement Copy trait
1621 fn borrow(val: &Value) {}
1623 fn eat(val: Value) {}
1627 let ref_to_val: &Value = &x;
1628 eat(x); // it will be copied here.
1633 You can find more information about borrowing in the rust-book:
1634 http://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html
1638 This error occurs when an attempt is made to assign to a borrowed value.
1640 Example of erroneous code:
1642 ```compile_fail,E0506
1648 let mut fancy_num = FancyNum { num: 5 };
1649 let fancy_ref = &fancy_num;
1650 fancy_num = FancyNum { num: 6 };
1651 // error: cannot assign to `fancy_num` because it is borrowed
1653 println!("Num: {}, Ref: {}", fancy_num.num, fancy_ref.num);
1657 Because `fancy_ref` still holds a reference to `fancy_num`, `fancy_num` can't
1658 be assigned to a new value as it would invalidate the reference.
1660 Alternatively, we can move out of `fancy_num` into a second `fancy_num`:
1668 let mut fancy_num = FancyNum { num: 5 };
1669 let moved_num = fancy_num;
1670 fancy_num = FancyNum { num: 6 };
1672 println!("Num: {}, Moved num: {}", fancy_num.num, moved_num.num);
1676 If the value has to be borrowed, try limiting the lifetime of the borrow using
1685 let mut fancy_num = FancyNum { num: 5 };
1688 let fancy_ref = &fancy_num;
1689 println!("Ref: {}", fancy_ref.num);
1692 // Works because `fancy_ref` is no longer in scope
1693 fancy_num = FancyNum { num: 6 };
1694 println!("Num: {}", fancy_num.num);
1698 Or by moving the reference into a function:
1706 let mut fancy_num = FancyNum { num: 5 };
1708 print_fancy_ref(&fancy_num);
1710 // Works because function borrow has ended
1711 fancy_num = FancyNum { num: 6 };
1712 println!("Num: {}", fancy_num.num);
1715 fn print_fancy_ref(fancy_ref: &FancyNum){
1716 println!("Ref: {}", fancy_ref.num);
1722 You tried to move out of a value which was borrowed. Erroneous code example:
1724 ```compile_fail,E0507
1725 use std::cell::RefCell;
1727 struct TheDarkKnight;
1729 impl TheDarkKnight {
1730 fn nothing_is_true(self) {}
1734 let x = RefCell::new(TheDarkKnight);
1736 x.borrow().nothing_is_true(); // error: cannot move out of borrowed content
1740 Here, the `nothing_is_true` method takes the ownership of `self`. However,
1741 `self` cannot be moved because `.borrow()` only provides an `&TheDarkKnight`,
1742 which is a borrow of the content owned by the `RefCell`. To fix this error,
1743 you have three choices:
1745 * Try to avoid moving the variable.
1746 * Somehow reclaim the ownership.
1747 * Implement the `Copy` trait on the type.
1752 use std::cell::RefCell;
1754 struct TheDarkKnight;
1756 impl TheDarkKnight {
1757 fn nothing_is_true(&self) {} // First case, we don't take ownership
1761 let x = RefCell::new(TheDarkKnight);
1763 x.borrow().nothing_is_true(); // ok!
1770 use std::cell::RefCell;
1772 struct TheDarkKnight;
1774 impl TheDarkKnight {
1775 fn nothing_is_true(self) {}
1779 let x = RefCell::new(TheDarkKnight);
1780 let x = x.into_inner(); // we get back ownership
1782 x.nothing_is_true(); // ok!
1789 use std::cell::RefCell;
1791 #[derive(Clone, Copy)] // we implement the Copy trait
1792 struct TheDarkKnight;
1794 impl TheDarkKnight {
1795 fn nothing_is_true(self) {}
1799 let x = RefCell::new(TheDarkKnight);
1801 x.borrow().nothing_is_true(); // ok!
1805 Moving a member out of a mutably borrowed struct will also cause E0507 error:
1807 ```compile_fail,E0507
1808 struct TheDarkKnight;
1810 impl TheDarkKnight {
1811 fn nothing_is_true(self) {}
1815 knight: TheDarkKnight
1819 let mut cave = Batcave {
1820 knight: TheDarkKnight
1822 let borrowed = &mut cave;
1824 borrowed.knight.nothing_is_true(); // E0507
1828 It is fine only if you put something back. `mem::replace` can be used for that:
1831 # struct TheDarkKnight;
1832 # impl TheDarkKnight { fn nothing_is_true(self) {} }
1833 # struct Batcave { knight: TheDarkKnight }
1836 let mut cave = Batcave {
1837 knight: TheDarkKnight
1839 let borrowed = &mut cave;
1841 mem::replace(&mut borrowed.knight, TheDarkKnight).nothing_is_true(); // ok!
1844 You can find more information about borrowing in the rust-book:
1845 http://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html
1849 A value was moved out of a non-copy fixed-size array.
1851 Example of erroneous code:
1853 ```compile_fail,E0508
1857 let array = [NonCopy; 1];
1858 let _value = array[0]; // error: cannot move out of type `[NonCopy; 1]`,
1859 // a non-copy fixed-size array
1863 The first element was moved out of the array, but this is not
1864 possible because `NonCopy` does not implement the `Copy` trait.
1866 Consider borrowing the element instead of moving it:
1872 let array = [NonCopy; 1];
1873 let _value = &array[0]; // Borrowing is allowed, unlike moving.
1877 Alternatively, if your type implements `Clone` and you need to own the value,
1878 consider borrowing and then cloning:
1885 let array = [NonCopy; 1];
1886 // Now you can clone the array element.
1887 let _value = array[0].clone();
1893 This error occurs when an attempt is made to move out of a value whose type
1894 implements the `Drop` trait.
1896 Example of erroneous code:
1898 ```compile_fail,E0509
1907 impl Drop for DropStruct {
1908 fn drop(&mut self) {
1909 // Destruct DropStruct, possibly using FancyNum
1914 let drop_struct = DropStruct{fancy: FancyNum{num: 5}};
1915 let fancy_field = drop_struct.fancy; // Error E0509
1916 println!("Fancy: {}", fancy_field.num);
1917 // implicit call to `drop_struct.drop()` as drop_struct goes out of scope
1921 Here, we tried to move a field out of a struct of type `DropStruct` which
1922 implements the `Drop` trait. However, a struct cannot be dropped if one or
1923 more of its fields have been moved.
1925 Structs implementing the `Drop` trait have an implicit destructor that gets
1926 called when they go out of scope. This destructor may use the fields of the
1927 struct, so moving out of the struct could make it impossible to run the
1928 destructor. Therefore, we must think of all values whose type implements the
1929 `Drop` trait as single units whose fields cannot be moved.
1931 This error can be fixed by creating a reference to the fields of a struct,
1932 enum, or tuple using the `ref` keyword:
1943 impl Drop for DropStruct {
1944 fn drop(&mut self) {
1945 // Destruct DropStruct, possibly using FancyNum
1950 let drop_struct = DropStruct{fancy: FancyNum{num: 5}};
1951 let ref fancy_field = drop_struct.fancy; // No more errors!
1952 println!("Fancy: {}", fancy_field.num);
1953 // implicit call to `drop_struct.drop()` as drop_struct goes out of scope
1957 Note that this technique can also be used in the arms of a match expression:
1968 impl Drop for DropEnum {
1969 fn drop(&mut self) {
1970 // Destruct DropEnum, possibly using FancyNum
1975 // Creates and enum of type `DropEnum`, which implements `Drop`
1976 let drop_enum = DropEnum::Fancy(FancyNum{num: 10});
1978 // Creates a reference to the inside of `DropEnum::Fancy`
1979 DropEnum::Fancy(ref fancy_field) => // No error!
1980 println!("It was fancy-- {}!", fancy_field.num),
1982 // implicit call to `drop_enum.drop()` as drop_enum goes out of scope
1988 Cannot mutate place in this match guard.
1990 When matching on a variable it cannot be mutated in the match guards, as this
1991 could cause the match to be non-exhaustive:
1993 ```compile_fail,E0510
1994 #![feature(nll, bind_by_move_pattern_guards)]
1995 let mut x = Some(0);
1998 Some(_) if { x = None; false } => (),
1999 Some(v) => (), // No longer matches
2003 Here executing `x = None` would modify the value being matched and require us
2004 to go "back in time" to the `None` arm.
2008 When matching against an exclusive range, the compiler verifies that the range
2009 is non-empty. Exclusive range patterns include the start point but not the end
2010 point, so this is equivalent to requiring the start of the range to be less
2011 than the end of the range.
2017 // This range is ok, albeit pointless.
2019 // This range is empty, and the compiler can tell.
2026 Cannot return value that references local variable
2028 Local variables, function parameters and temporaries are all dropped before the
2029 end of the function body. So a reference to them cannot be returned.
2031 ```compile_fail,E0515
2033 fn get_dangling_reference() -> &'static i32 {
2039 ```compile_fail,E0515
2041 use std::slice::Iter;
2042 fn get_dangling_iterator<'a>() -> Iter<'a, i32> {
2043 let v = vec![1, 2, 3];
2048 Consider returning an owned value instead:
2051 use std::vec::IntoIter;
2053 fn get_integer() -> i32 {
2058 fn get_owned_iterator() -> IntoIter<i32> {
2059 let v = vec![1, 2, 3];
2066 #### Note: this error code is no longer emitted by the compiler.
2068 Closures cannot mutate immutable captured variables.
2070 Erroneous code example:
2072 ```compile_fail,E0594
2073 let x = 3; // error: closure cannot assign to immutable local variable `x`
2074 let mut c = || { x += 1 };
2077 Make the variable binding mutable:
2080 let mut x = 3; // ok!
2081 let mut c = || { x += 1 };
2086 This error occurs because you tried to mutably borrow a non-mutable variable.
2088 Example of erroneous code:
2090 ```compile_fail,E0596
2092 let y = &mut x; // error: cannot borrow mutably
2095 In here, `x` isn't mutable, so when we try to mutably borrow it in `y`, it
2096 fails. To fix this error, you need to make `x` mutable:
2100 let y = &mut x; // ok!
2105 This error occurs because a value was dropped while it was still borrowed
2107 Example of erroneous code:
2109 ```compile_fail,E0597
2114 let mut x = Foo { x: None };
2117 x.x = Some(&y); // error: `y` does not live long enough
2119 println!("{:?}", x.x);
2122 In here, `y` is dropped at the end of the inner scope, but it is borrowed by
2123 `x` until the `println`. To fix the previous example, just remove the scope
2124 so that `y` isn't dropped until after the println
2131 let mut x = Foo { x: None };
2136 println!("{:?}", x.x);
2141 This error occurs because a borrow in a generator persists across a
2144 ```compile_fail,E0626
2145 # #![feature(generators, generator_trait, pin)]
2146 # use std::ops::Generator;
2147 # use std::pin::Pin;
2149 let a = &String::new(); // <-- This borrow...
2150 yield (); // ...is still in scope here, when the yield occurs.
2153 Pin::new(&mut b).resume();
2156 At present, it is not permitted to have a yield that occurs while a
2157 borrow is still in scope. To resolve this error, the borrow must
2158 either be "contained" to a smaller scope that does not overlap the
2159 yield or else eliminated in another way. So, for example, we might
2160 resolve the previous example by removing the borrow and just storing
2161 the integer by value:
2164 # #![feature(generators, generator_trait, pin)]
2165 # use std::ops::Generator;
2166 # use std::pin::Pin;
2172 Pin::new(&mut b).resume();
2175 This is a very simple case, of course. In more complex cases, we may
2176 wish to have more than one reference to the value that was borrowed --
2177 in those cases, something like the `Rc` or `Arc` types may be useful.
2179 This error also frequently arises with iteration:
2181 ```compile_fail,E0626
2182 # #![feature(generators, generator_trait, pin)]
2183 # use std::ops::Generator;
2184 # use std::pin::Pin;
2186 let v = vec![1,2,3];
2187 for &x in &v { // <-- borrow of `v` is still in scope...
2188 yield x; // ...when this yield occurs.
2191 Pin::new(&mut b).resume();
2194 Such cases can sometimes be resolved by iterating "by value" (or using
2195 `into_iter()`) to avoid borrowing:
2198 # #![feature(generators, generator_trait, pin)]
2199 # use std::ops::Generator;
2200 # use std::pin::Pin;
2202 let v = vec![1,2,3];
2203 for x in v { // <-- Take ownership of the values instead!
2204 yield x; // <-- Now yield is OK.
2207 Pin::new(&mut b).resume();
2210 If taking ownership is not an option, using indices can work too:
2213 # #![feature(generators, generator_trait, pin)]
2214 # use std::ops::Generator;
2215 # use std::pin::Pin;
2217 let v = vec![1,2,3];
2218 let len = v.len(); // (*)
2220 let x = v[i]; // (*)
2221 yield x; // <-- Now yield is OK.
2224 Pin::new(&mut b).resume();
2226 // (*) -- Unfortunately, these temporaries are currently required.
2227 // See <https://github.com/rust-lang/rust/issues/43122>.
2232 This error occurs because a borrow of a thread-local variable was made inside a
2233 function which outlived the lifetime of the function.
2235 Example of erroneous code:
2237 ```compile_fail,E0712
2239 #![feature(thread_local)]
2245 let a = &FOO; // error: thread-local variable borrowed past end of function
2247 std::thread::spawn(move || {
2255 This error occurs when an attempt is made to borrow state past the end of the
2256 lifetime of a type that implements the `Drop` trait.
2258 Example of erroneous code:
2260 ```compile_fail,E0713
2263 pub struct S<'a> { data: &'a mut String }
2265 impl<'a> Drop for S<'a> {
2266 fn drop(&mut self) { self.data.push_str("being dropped"); }
2269 fn demo<'a>(s: S<'a>) -> &'a mut String { let p = &mut *s.data; p }
2272 Here, `demo` tries to borrow the string data held within its
2273 argument `s` and then return that borrow. However, `S` is
2274 declared as implementing `Drop`.
2276 Structs implementing the `Drop` trait have an implicit destructor that
2277 gets called when they go out of scope. This destructor gets exclusive
2278 access to the fields of the struct when it runs.
2280 This means that when `s` reaches the end of `demo`, its destructor
2281 gets exclusive access to its `&mut`-borrowed string data. allowing
2282 another borrow of that string data (`p`), to exist across the drop of
2283 `s` would be a violation of the principle that `&mut`-borrows have
2284 exclusive, unaliased access to their referenced data.
2286 This error can be fixed by changing `demo` so that the destructor does
2287 not run while the string-data is borrowed; for example by taking `S`
2293 pub struct S<'a> { data: &'a mut String }
2295 impl<'a> Drop for S<'a> {
2296 fn drop(&mut self) { self.data.push_str("being dropped"); }
2299 fn demo<'a>(s: &'a mut S<'a>) -> &'a mut String { let p = &mut *(*s).data; p }
2302 Note that this approach needs a reference to S with lifetime `'a`.
2303 Nothing shorter than `'a` will suffice: a shorter lifetime would imply
2304 that after `demo` finishes executing, something else (such as the
2305 destructor!) could access `s.data` after the end of that shorter
2306 lifetime, which would again violate the `&mut`-borrow's exclusive
2311 This error indicates that a temporary value is being dropped
2312 while a borrow is still in active use.
2314 Erroneous code example:
2316 ```compile_fail,E0716
2318 fn foo() -> i32 { 22 }
2319 fn bar(x: &i32) -> &i32 { x }
2320 let p = bar(&foo());
2321 // ------ creates a temporary
2325 Here, the expression `&foo()` is borrowing the expression
2326 `foo()`. As `foo()` is a call to a function, and not the name of
2327 a variable, this creates a **temporary** -- that temporary stores
2328 the return value from `foo()` so that it can be borrowed.
2329 You could imagine that `let p = bar(&foo());` is equivalent
2332 ```compile_fail,E0597
2333 # fn foo() -> i32 { 22 }
2334 # fn bar(x: &i32) -> &i32 { x }
2336 let tmp = foo(); // the temporary
2338 }; // <-- tmp is freed as we exit this block
2342 Whenever a temporary is created, it is automatically dropped (freed)
2343 according to fixed rules. Ordinarily, the temporary is dropped
2344 at the end of the enclosing statement -- in this case, after the `let`.
2345 This is illustrated in the example above by showing that `tmp` would
2346 be freed as we exit the block.
2348 To fix this problem, you need to create a local variable
2349 to store the value in rather than relying on a temporary.
2350 For example, you might change the original program to
2354 fn foo() -> i32 { 22 }
2355 fn bar(x: &i32) -> &i32 { x }
2356 let value = foo(); // dropped at the end of the enclosing block
2357 let p = bar(&value);
2361 By introducing the explicit `let value`, we allocate storage
2362 that will last until the end of the enclosing block (when `value`
2363 goes out of scope). When we borrow `&value`, we are borrowing a
2364 local variable that already exists, and hence no temporary is created.
2366 Temporaries are not always dropped at the end of the enclosing
2367 statement. In simple cases where the `&` expression is immediately
2368 stored into a variable, the compiler will automatically extend
2369 the lifetime of the temporary until the end of the enclosing
2370 block. Therefore, an alternative way to fix the original
2371 program is to write `let tmp = &foo()` and not `let tmp = foo()`:
2374 fn foo() -> i32 { 22 }
2375 fn bar(x: &i32) -> &i32 { x }
2381 Here, we are still borrowing `foo()`, but as the borrow is assigned
2382 directly into a variable, the temporary will not be dropped until
2383 the end of the enclosing block. Similar rules apply when temporaries
2384 are stored into aggregate structures like a tuple or struct:
2387 // Here, two temporaries are created, but
2388 // as they are stored directly into `value`,
2389 // they are not dropped until the end of the
2391 fn foo() -> i32 { 22 }
2392 let value = (&foo(), &foo());
2397 An feature unstable in `const` contexts was used.
2399 Erroneous code example:
2401 ```compile_fail,E0723
2406 const fn foo() -> impl T { // error: `impl Trait` in const fn is unstable
2411 To enable this feature on a nightly version of rustc, add the `const_fn`
2415 #![feature(const_fn)]
2421 const fn foo() -> impl T {
2428 Support for Non-Lexical Lifetimes (NLL) has been included in the Rust compiler
2429 since 1.31, and has been enabled on the 2015 edition since 1.36. The new borrow
2430 checker for NLL uncovered some bugs in the old borrow checker, which in some
2431 cases allowed unsound code to compile, resulting in memory safety issues.
2435 Change your code so the warning does no longer trigger. For backwards
2436 compatibility, this unsound code may still compile (with a warning) right now.
2437 However, at some point in the future, the compiler will no longer accept this
2438 code and will throw a hard error.
2440 ### Shouldn't you fix the old borrow checker?
2442 The old borrow checker has known soundness issues that are basically impossible
2443 to fix. The new NLL-based borrow checker is the fix.
2445 ### Can I turn these warnings into errors by denying a lint?
2449 ### When are these warnings going to turn into errors?
2451 No formal timeline for turning the warnings into errors has been set. See
2452 [GitHub issue 58781](https://github.com/rust-lang/rust/issues/58781) for more
2455 ### Why do I get this message with code that doesn't involve borrowing?
2457 There are some known bugs that trigger this message.
2461 register_diagnostics! {
2462 // E0298, // cannot compare constants
2463 // E0299, // mismatched types between arms
2464 // E0471, // constant evaluation error (in pattern)
2465 // E0385, // {} in an aliasable location
2466 E0493, // destructors cannot be evaluated at compile-time
2467 E0521, // borrowed data escapes outside of closure
2468 E0524, // two closures require unique access to `..` at the same time
2469 E0526, // shuffle indices are not constant
2470 E0594, // cannot assign to {}
2471 E0598, // lifetime of {} is too short to guarantee its contents can be...
2472 E0625, // thread-local statics cannot be accessed at compile-time