1 // Copyright 2014 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 // Error messages for EXXXX errors.
14 // Each message should start and end with a new line, and be wrapped to 80 characters.
15 // In vim you can `:set tw=80` and use `gq` to wrap paragraphs. Use `:set tw=0` to disable.
16 register_long_diagnostics! {
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) => {/* ... */}
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 This error indicates that an empty match expression is invalid because the type
45 it is matching on is non-empty (there exist values of this type). In safe code
46 it is impossible to create an instance of an empty type, so empty match
47 expressions are almost never desired. This error is typically fixed by adding
48 one or more cases to the match expression.
50 An example of an empty type is `enum Empty { }`. So, the following will work:
67 fn foo(x: Option<String>) {
76 Not-a-Number (NaN) values cannot be compared for equality and hence can never
77 match the input to a match expression. So, the following will not compile:
80 const NAN: f32 = 0.0 / 0.0;
90 To match against NaN values, you should instead use the `is_nan()` method in a
97 x if x.is_nan() => { /* ... */ }
104 This error indicates that the compiler cannot guarantee a matching pattern for
105 one or more possible inputs to a match expression. Guaranteed matches are
106 required in order to assign values to match expressions, or alternatively,
107 determine the flow of execution. Erroneous code example:
115 let x = Terminator::HastaLaVistaBaby;
117 match x { // error: non-exhaustive patterns: `HastaLaVistaBaby` not covered
118 Terminator::TalkToMyHand => {}
122 If you encounter this error you must alter your patterns so that every possible
123 value of the input type is matched. For types with a small number of variants
124 (like enums) you should probably cover all cases explicitly. Alternatively, the
125 underscore `_` wildcard pattern can be added after all other patterns to match
126 "anything else". Example:
134 let x = Terminator::HastaLaVistaBaby;
137 Terminator::TalkToMyHand => {}
138 Terminator::HastaLaVistaBaby => {}
144 Terminator::TalkToMyHand => {}
151 Patterns used to bind names must be irrefutable, that is, they must guarantee
152 that a name will be extracted in all cases. Erroneous code example:
157 // error: refutable pattern in local binding: `None` not covered
160 If you encounter this error you probably need to use a `match` or `if let` to
161 deal with the possibility of failure. Example:
182 This error indicates that the bindings in a match arm would require a value to
183 be moved into more than one location, thus violating unique ownership. Code
184 like the following is invalid as it requires the entire `Option<String>` to be
185 moved into a variable called `op_string` while simultaneously requiring the
186 inner `String` to be moved into a variable called `s`.
189 let x = Some("s".to_string());
192 op_string @ Some(s) => {},
197 See also the error E0303.
201 Names bound in match arms retain their type in pattern guards. As such, if a
202 name is bound by move in a pattern, it should also be moved to wherever it is
203 referenced in the pattern guard code. Doing so however would prevent the name
204 from being available in the body of the match arm. Consider the following:
207 match Some("hi".to_string()) {
208 Some(s) if s.len() == 0 => {}, // use s.
213 The variable `s` has type `String`, and its use in the guard is as a variable of
214 type `String`. The guard code effectively executes in a separate scope to the
215 body of the arm, so the value would be moved into this anonymous scope and
216 therefore become unavailable in the body of the arm. Although this example seems
217 innocuous, the problem is most clear when considering functions that take their
221 match Some("hi".to_string()) {
222 Some(s) if { drop(s); false } => (),
223 Some(s) => {}, // use s.
228 The value would be dropped in the guard then become unavailable not only in the
229 body of that arm but also in all subsequent arms! The solution is to bind by
230 reference when using guards or refactor the entire expression, perhaps by
231 putting the condition inside the body of the arm.
235 In a pattern, all values that don't implement the `Copy` trait have to be bound
236 the same way. The goal here is to avoid binding simultaneously by-move and
239 This limitation may be removed in a future version of Rust.
241 Erroneous code example:
246 let x = Some((X { x: () }, X { x: () }));
248 Some((y, ref z)) => {},
253 You have two solutions:
255 Solution #1: Bind the pattern's values the same way.
260 let x = Some((X { x: () }, X { x: () }));
262 Some((ref y, ref z)) => {},
263 // or Some((y, z)) => {}
268 Solution #2: Implement the `Copy` trait for the `X` structure.
270 However, please keep in mind that the first solution should be preferred.
273 #[derive(Clone, Copy)]
276 let x = Some((X { x: () }, X { x: () }));
278 Some((y, ref z)) => {},
285 This error indicates that an attempt was made to divide by zero (or take the
286 remainder of a zero divisor) in a static or constant expression. Erroneous
290 const X: i32 = 42 / 0;
291 // error: attempted to divide by zero in a constant expression
296 Trait objects like `Box<Trait>` can only be constructed when certain
297 requirements are satisfied by the trait in question.
299 Trait objects are a form of dynamic dispatch and use a dynamically sized type
300 for the inner type. So, for a given trait `Trait`, when `Trait` is treated as a
301 type, as in `Box<Trait>`, the inner type is 'unsized'. In such cases the boxed
302 pointer is a 'fat pointer' that contains an extra pointer to a table of methods
303 (among other things) for dynamic dispatch. This design mandates some
304 restrictions on the types of traits that are allowed to be used in trait
305 objects, which are collectively termed as 'object safety' rules.
307 Attempting to create a trait object for a non object-safe trait will trigger
310 There are various rules:
312 ### The trait cannot require `Self: Sized`
314 When `Trait` is treated as a type, the type does not implement the special
315 `Sized` trait, because the type does not have a known size at compile time and
316 can only be accessed behind a pointer. Thus, if we have a trait like the
320 trait Foo where Self: Sized {
325 We cannot create an object of type `Box<Foo>` or `&Foo` since in this case
326 `Self` would not be `Sized`.
328 Generally, `Self : Sized` is used to indicate that the trait should not be used
329 as a trait object. If the trait comes from your own crate, consider removing
332 ### Method references the `Self` type in its arguments or return type
334 This happens when a trait has a method like the following:
338 fn foo(&self) -> Self;
341 impl Trait for String {
342 fn foo(&self) -> Self {
348 fn foo(&self) -> Self {
354 (Note that `&self` and `&mut self` are okay, it's additional `Self` types which
357 In such a case, the compiler cannot predict the return type of `foo()` in a
358 situation like the following:
362 fn foo(&self) -> Self;
365 fn call_foo(x: Box<Trait>) {
366 let y = x.foo(); // What type is y?
371 If only some methods aren't object-safe, you can add a `where Self: Sized` bound
372 on them to mark them as explicitly unavailable to trait objects. The
373 functionality will still be available to all other implementers, including
374 `Box<Trait>` which is itself sized (assuming you `impl Trait for Box<Trait>`).
378 fn foo(&self) -> Self where Self: Sized;
383 Now, `foo()` can no longer be called on a trait object, but you will now be
384 allowed to make a trait object, and that will be able to call any object-safe
385 methods". With such a bound, one can still call `foo()` on types implementing
386 that trait that aren't behind trait objects.
388 ### Method has generic type parameters
390 As mentioned before, trait objects contain pointers to method tables. So, if we
398 impl Trait for String {
412 At compile time each implementation of `Trait` will produce a table containing
413 the various methods (and other items) related to the implementation.
415 This works fine, but when the method gains generic parameters, we can have a
418 Usually, generic parameters get _monomorphized_. For example, if I have
426 The machine code for `foo::<u8>()`, `foo::<bool>()`, `foo::<String>()`, or any
427 other type substitution is different. Hence the compiler generates the
428 implementation on-demand. If you call `foo()` with a `bool` parameter, the
429 compiler will only generate code for `foo::<bool>()`. When we have additional
430 type parameters, the number of monomorphized implementations the compiler
431 generates does not grow drastically, since the compiler will only generate an
432 implementation if the function is called with unparametrized substitutions
433 (i.e., substitutions where none of the substituted types are themselves
436 However, with trait objects we have to make a table containing _every_ object
437 that implements the trait. Now, if it has type parameters, we need to add
438 implementations for every type that implements the trait, and there could
439 theoretically be an infinite number of types.
445 fn foo<T>(&self, on: T);
449 impl Trait for String {
450 fn foo<T>(&self, on: T) {
456 fn foo<T>(&self, on: T) {
461 // 8 more implementations
464 Now, if we have the following code:
467 fn call_foo(thing: Box<Trait>) {
468 thing.foo(true); // this could be any one of the 8 types above
474 We don't just need to create a table of all implementations of all methods of
475 `Trait`, we need to create such a table, for each different type fed to
476 `foo()`. In this case this turns out to be (10 types implementing `Trait`)*(3
477 types being fed to `foo()`) = 30 implementations!
479 With real world traits these numbers can grow drastically.
481 To fix this, it is suggested to use a `where Self: Sized` bound similar to the
482 fix for the sub-error above if you do not intend to call the method with type
487 fn foo<T>(&self, on: T) where Self: Sized;
492 If this is not an option, consider replacing the type parameter with another
493 trait object (e.g. if `T: OtherTrait`, use `on: Box<OtherTrait>`). If the number
494 of types you intend to feed to this method is limited, consider manually listing
495 out the methods of different types.
497 ### Method has no receiver
499 Methods that do not take a `self` parameter can't be called since there won't be
500 a way to get a pointer to the method table for them.
508 This could be called as `<Foo as Foo>::foo()`, which would not be able to pick
511 Adding a `Self: Sized` bound to these methods will generally make this compile.
515 fn foo() -> u8 where Self: Sized;
519 ### The trait cannot use `Self` as a type parameter in the supertrait listing
521 This is similar to the second sub-error, but subtler. It happens in situations
527 trait Trait: Super<Self> {
532 impl Super<Foo> for Foo{}
534 impl Trait for Foo {}
537 Here, the supertrait might have methods as follows:
541 fn get_a(&self) -> A; // note that this is object safe!
545 If the trait `Foo` was deriving from something like `Super<String>` or
546 `Super<T>` (where `Foo` itself is `Foo<T>`), this is okay, because given a type
547 `get_a()` will definitely return an object of that type.
549 However, if it derives from `Super<Self>`, even though `Super` is object safe,
550 the method `get_a()` would return an object of unknown type when called on the
551 function. `Self` type parameters let us make object safe traits no longer safe,
552 so they are forbidden when specifying supertraits.
554 There's no easy fix for this, generally code will need to be refactored so that
555 you no longer need to derive from `Super<Self>`.
559 When defining a recursive struct or enum, any use of the type being defined
560 from inside the definition must occur behind a pointer (like `Box` or `&`).
561 This is because structs and enums must have a well-defined size, and without
562 the pointer the size of the type would need to be unbounded.
564 Consider the following erroneous definition of a type for a list of bytes:
567 // error, invalid recursive struct type
570 tail: Option<ListNode>,
574 This type cannot have a well-defined size, because it needs to be arbitrarily
575 large (since we would be able to nest `ListNode`s to any depth). Specifically,
578 size of `ListNode` = 1 byte for `head`
579 + 1 byte for the discriminant of the `Option`
583 One way to fix this is by wrapping `ListNode` in a `Box`, like so:
588 tail: Option<Box<ListNode>>,
592 This works because `Box` is a pointer, so its size is well-known.
596 You tried to give a type parameter to a type which doesn't need it. Erroneous
600 type X = u32<i32>; // error: type parameters are not allowed on this type
603 Please check that you used the correct type and recheck its definition. Perhaps
604 it doesn't need the type parameter.
609 type X = u32; // this compiles
612 Note that type parameters for enum-variant constructors go after the variant,
613 not after the enum (Option::None::<u32>, not Option::<u32>::None).
617 You tried to give a lifetime parameter to a type which doesn't need it.
618 Erroneous code example:
621 type X = u32<'static>; // error: lifetime parameters are not allowed on
625 Please check that the correct type was used and recheck its definition; perhaps
626 it doesn't need the lifetime parameter. Example:
634 Using unsafe functionality is potentially dangerous and disallowed by safety
637 * Dereferencing raw pointers
638 * Calling functions via FFI
639 * Calling functions marked unsafe
641 These safety checks can be relaxed for a section of the code by wrapping the
642 unsafe instructions with an `unsafe` block. For instance:
645 unsafe fn f() { return; }
652 See also https://doc.rust-lang.org/book/unsafe.html
655 // This shouldn't really ever trigger since the repeated value error comes first
657 A binary can only have one entry point, and by default that entry point is the
658 function `main()`. If there are multiple such functions, please rename one.
662 This error indicates that the compiler found multiple functions with the
663 `#[main]` attribute. This is an error because there must be a unique entry
664 point into a Rust program.
668 This error indicates that the compiler found multiple functions with the
669 `#[start]` attribute. This is an error because there must be a unique entry
670 point into a Rust program.
673 // FIXME link this to the relevant turpl chapters for instilling fear of the
674 // transmute gods in the user
676 There are various restrictions on transmuting between types in Rust; for example
677 types being transmuted must have the same size. To apply all these restrictions,
678 the compiler must know the exact types that may be transmuted. When type
679 parameters are involved, this cannot always be done.
681 So, for example, the following is not allowed:
684 struct Foo<T>(Vec<T>);
686 fn foo<T>(x: Vec<T>) {
687 // we are transmuting between Vec<T> and Foo<T> here
688 let y: Foo<T> = unsafe { transmute(x) };
689 // do something with y
693 In this specific case there's a good chance that the transmute is harmless (but
694 this is not guaranteed by Rust). However, when alignment and enum optimizations
695 come into the picture, it's quite likely that the sizes may or may not match
696 with different type parameter substitutions. It's not possible to check this for
697 _all_ possible types, so `transmute()` simply only accepts types without any
698 unsubstituted type parameters.
700 If you need this, there's a good chance you're doing something wrong. Keep in
701 mind that Rust doesn't guarantee much about the layout of different structs
702 (even two structs with identical declarations may have different layouts). If
703 there is a solution that avoids the transmute entirely, try it instead.
705 If it's possible, hand-monomorphize the code by writing the function for each
706 possible type substitution. It's possible to use traits to do this cleanly,
710 struct Foo<T>(Vec<T>);
712 trait MyTransmutableType {
713 fn transmute(Vec<Self>) -> Foo<Self>;
716 impl MyTransmutableType for u8 {
717 fn transmute(x: Foo<u8>) -> Vec<u8> {
722 impl MyTransmutableType for String {
723 fn transmute(x: Foo<String>) -> Vec<String> {
728 // ... more impls for the types you intend to transmute
730 fn foo<T: MyTransmutableType>(x: Vec<T>) {
731 let y: Foo<T> = <T as MyTransmutableType>::transmute(x);
732 // do something with y
736 Each impl will be checked for a size match in the transmute as usual, and since
737 there are no unbound type parameters involved, this should compile unless there
738 is a size mismatch in one of the impls.
740 It is also possible to manually transmute:
743 ptr::read(&v as *const _ as *const SomeType) // `v` transmuted to `SomeType`
746 Note that this does not move `v` (unlike `transmute`), and may need a
747 call to `mem::forget(v)` in case you want to avoid destructors being called.
751 Lang items are already implemented in the standard library. Unless you are
752 writing a free-standing application (e.g. a kernel), you do not need to provide
755 You can build a free-standing crate by adding `#![no_std]` to the crate
762 See also https://doc.rust-lang.org/book/no-stdlib.html
766 `const` and `static` mean different things. A `const` is a compile-time
767 constant, an alias for a literal value. This property means you can match it
768 directly within a pattern.
770 The `static` keyword, on the other hand, guarantees a fixed location in memory.
771 This does not always mean that the value is constant. For example, a global
772 mutex can be declared `static` as well.
774 If you want to match against a `static`, consider using a guard instead:
777 static FORTY_TWO: i32 = 42;
780 Some(x) if x == FORTY_TWO => {}
787 An if-let pattern attempts to match the pattern, and enters the body if the
788 match was successful. If the match is irrefutable (when it cannot fail to
789 match), use a regular `let`-binding instead. For instance:
792 struct Irrefutable(i32);
793 let irr = Irrefutable(0);
795 // This fails to compile because the match is irrefutable.
796 if let Irrefutable(x) = irr {
797 // This body will always be executed.
805 struct Irrefutable(i32);
806 let irr = Irrefutable(0);
808 let Irrefutable(x) = irr;
814 A while-let pattern attempts to match the pattern, and enters the body if the
815 match was successful. If the match is irrefutable (when it cannot fail to
816 match), use a regular `let`-binding inside a `loop` instead. For instance:
819 struct Irrefutable(i32);
820 let irr = Irrefutable(0);
822 // This fails to compile because the match is irrefutable.
823 while let Irrefutable(x) = irr {
830 struct Irrefutable(i32);
831 let irr = Irrefutable(0);
834 let Irrefutable(x) = irr;
841 Enum variants are qualified by default. For example, given this type:
850 You would match it using:
866 If you don't qualify the names, the code will bind new variables named "GET" and
867 "POST" instead. This behavior is likely not what you want, so `rustc` warns when
870 Qualified names are good practice, and most code works well with them. But if
871 you prefer them unqualified, you can import the variants into scope:
875 enum Method { GET, POST }
878 If you want others to be able to import variants from your module directly, use
883 enum Method { GET, POST }
888 An associated type binding was done outside of the type parameter declaration
889 and `where` clause. Erroneous code example:
894 fn boo(&self) -> <Self as Foo>::A;
901 fn boo(&self) -> usize { 42 }
904 fn baz<I>(x: &<I as Foo<A=Bar>>::A) {}
905 // error: associated type bindings are not allowed here
908 To solve this error, please move the type bindings in the type parameter
912 fn baz<I: Foo<A=Bar>>(x: &<I as Foo>::A) {} // ok!
915 Or in the `where` clause:
918 fn baz<I>(x: &<I as Foo>::A) where I: Foo<A=Bar> {}
923 When using a lifetime like `'a` in a type, it must be declared before being
926 These two examples illustrate the problem:
929 // error, use of undeclared lifetime name `'a`
930 fn foo(x: &'a str) { }
933 // error, use of undeclared lifetime name `'a`
938 These can be fixed by declaring lifetime parameters:
941 fn foo<'a>(x: &'a str) {}
950 Declaring certain lifetime names in parameters is disallowed. For example,
951 because the `'static` lifetime is a special built-in lifetime name denoting
952 the lifetime of the entire program, this is an error:
955 // error, invalid lifetime parameter name `'static`
956 fn foo<'static>(x: &'static str) { }
961 A lifetime name cannot be declared more than once in the same scope. For
965 // error, lifetime name `'a` declared twice in the same scope
966 fn foo<'a, 'b, 'a>(x: &'a str, y: &'b str) { }
971 An unknown external lang item was used. Erroneous code example:
974 #![feature(lang_items)]
977 #[lang = "cake"] // error: unknown external lang item: `cake`
982 A list of available external lang items is available in
983 `src/librustc/middle/weak_lang_items.rs`. Example:
986 #![feature(lang_items)]
989 #[lang = "panic_fmt"] // ok!
996 Functions must eventually return a value of their return type. For example, in
997 the following function:
1000 fn foo(x: u8) -> u8 {
1002 x // alternatively, `return x`
1008 If the condition is true, the value `x` is returned, but if the condition is
1009 false, control exits the `if` block and reaches a place where nothing is being
1010 returned. All possible control paths must eventually return a `u8`, which is not
1013 An easy fix for this in a complicated function is to specify a default return
1017 fn foo(x: u8) -> u8 {
1019 x // alternatively, `return x`
1021 // lots of other if branches
1022 0 // return 0 if all else fails
1026 It is advisable to find out what the unhandled cases are and check for them,
1027 returning an appropriate value or panicking if necessary.
1031 Rust lets you define functions which are known to never return, i.e. are
1032 'diverging', by marking its return type as `!`.
1034 For example, the following functions never return:
1042 foo() // foo() is diverging, so this will diverge too
1046 panic!(); // this macro internally expands to a call to a diverging function
1050 Such functions can be used in a place where a value is expected without
1051 returning a value of that type, for instance:
1063 _ => foo() // diverging function called here
1069 If the third arm of the match block is reached, since `foo()` doesn't ever
1070 return control to the match block, it is fine to use it in a place where an
1071 integer was expected. The `match` block will never finish executing, and any
1072 point where `y` (like the print statement) is needed will not be reached.
1074 However, if we had a diverging function that actually does finish execution:
1082 Then we would have an unknown value for `y` in the following code:
1100 In the previous example, the print statement was never reached when the
1101 wildcard match arm was hit, so we were okay with `foo()` not returning an
1102 integer that we could set to `y`. But in this example, `foo()` actually does
1103 return control, so the print statement will be executed with an uninitialized
1106 Obviously we cannot have functions which are allowed to be used in such
1107 positions and yet can return control. So, if you are defining a function that
1108 returns `!`, make sure that there is no way for it to actually finish
1113 This is because of a type mismatch between the associated type of some
1114 trait (e.g. `T::Bar`, where `T` implements `trait Quux { type Bar; }`)
1115 and another type `U` that is required to be equal to `T::Bar`, but is not.
1118 Here is a basic example:
1121 trait Trait { type AssociatedType; }
1123 fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
1127 impl Trait for i8 { type AssociatedType = &'static str; }
1132 Here is that same example again, with some explanatory comments:
1135 trait Trait { type AssociatedType; }
1137 fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
1138 // ~~~~~~~~ ~~~~~~~~~~~~~~~~~~
1140 // This says `foo` can |
1141 // only be used with |
1143 // implements `Trait`. |
1145 // This says not only must
1146 // `T` be an impl of `Trait`
1147 // but also that the impl
1148 // must assign the type `u32`
1149 // to the associated type.
1153 impl Trait for i8 { type AssociatedType = &'static str; }
1154 ~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1159 // ... but it is an implementation
1160 // that assigns `&'static str` to
1161 // the associated type.
1164 // Here, we invoke `foo` with an `i8`, which does not satisfy
1165 // the constraint `<i8 as Trait>::AssociatedType=u32`, and
1166 // therefore the type-checker complains with this error code.
1169 Here is a more subtle instance of the same problem, that can
1170 arise with for-loops in Rust:
1173 let vs: Vec<i32> = vec![1, 2, 3, 4];
1182 The above fails because of an analogous type mismatch,
1183 though may be harder to see. Again, here are some
1184 explanatory comments for the same example:
1188 let vs = vec![1, 2, 3, 4];
1190 // `for`-loops use a protocol based on the `Iterator`
1191 // trait. Each item yielded in a `for` loop has the
1192 // type `Iterator::Item` -- that is, `Item` is the
1193 // associated type of the concrete iterator impl.
1197 // | We borrow `vs`, iterating over a sequence of
1198 // | *references* of type `&Elem` (where `Elem` is
1199 // | vector's element type). Thus, the associated
1200 // | type `Item` must be a reference `&`-type ...
1202 // ... and `v` has the type `Iterator::Item`, as dictated by
1203 // the `for`-loop protocol ...
1209 // ... but *here*, `v` is forced to have some integral type;
1210 // only types like `u8`,`i8`,`u16`,`i16`, et cetera can
1211 // match the pattern `1` ...
1216 // ... therefore, the compiler complains, because it sees
1217 // an attempt to solve the equations
1218 // `some integral-type` = type-of-`v`
1219 // = `Iterator::Item`
1220 // = `&Elem` (i.e. `some reference type`)
1222 // which cannot possibly all be true.
1228 To avoid those issues, you have to make the types match correctly.
1229 So we can fix the previous examples like this:
1233 trait Trait { type AssociatedType; }
1235 fn foo<T>(t: T) where T: Trait<AssociatedType = &'static str> {
1239 impl Trait for i8 { type AssociatedType = &'static str; }
1243 // For-Loop Example:
1244 let vs = vec![1, 2, 3, 4];
1255 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
1256 message for when a particular trait isn't implemented on a type placed in a
1257 position that needs that trait. For example, when the following code is
1261 fn foo<T: Index<u8>>(x: T){}
1263 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1264 trait Index<Idx> { ... }
1266 foo(true); // `bool` does not implement `Index<u8>`
1269 There will be an error about `bool` not implementing `Index<u8>`, followed by a
1270 note saying "the type `bool` cannot be indexed by `u8`".
1272 As you can see, you can specify type parameters in curly braces for
1273 substitution with the actual types (using the regular format string syntax) in
1274 a given situation. Furthermore, `{Self}` will substitute to the type (in this
1275 case, `bool`) that we tried to use.
1277 This error appears when the curly braces contain an identifier which doesn't
1278 match with any of the type parameters or the string `Self`. This might happen
1279 if you misspelled a type parameter, or if you intended to use literal curly
1280 braces. If it is the latter, escape the curly braces with a second curly brace
1281 of the same type; e.g. a literal `{` is `{{`.
1285 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
1286 message for when a particular trait isn't implemented on a type placed in a
1287 position that needs that trait. For example, when the following code is
1291 fn foo<T: Index<u8>>(x: T){}
1293 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1294 trait Index<Idx> { ... }
1296 foo(true); // `bool` does not implement `Index<u8>`
1299 there will be an error about `bool` not implementing `Index<u8>`, followed by a
1300 note saying "the type `bool` cannot be indexed by `u8`".
1302 As you can see, you can specify type parameters in curly braces for
1303 substitution with the actual types (using the regular format string syntax) in
1304 a given situation. Furthermore, `{Self}` will substitute to the type (in this
1305 case, `bool`) that we tried to use.
1307 This error appears when the curly braces do not contain an identifier. Please
1308 add one of the same name as a type parameter. If you intended to use literal
1309 braces, use `{{` and `}}` to escape them.
1313 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
1314 message for when a particular trait isn't implemented on a type placed in a
1315 position that needs that trait. For example, when the following code is
1319 fn foo<T: Index<u8>>(x: T){}
1321 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1322 trait Index<Idx> { ... }
1324 foo(true); // `bool` does not implement `Index<u8>`
1327 there will be an error about `bool` not implementing `Index<u8>`, followed by a
1328 note saying "the type `bool` cannot be indexed by `u8`".
1330 For this to work, some note must be specified. An empty attribute will not do
1331 anything, please remove the attribute or add some helpful note for users of the
1336 This error occurs when there was a recursive trait requirement that overflowed
1337 before it could be evaluated. Often this means that there is unbounded
1338 recursion in resolving some type bounds.
1340 For example, in the following code:
1347 impl<T> Foo for T where Bar<T>: Foo {}
1350 To determine if a `T` is `Foo`, we need to check if `Bar<T>` is `Foo`. However,
1351 to do this check, we need to determine that `Bar<Bar<T>>` is `Foo`. To
1352 determine this, we check if `Bar<Bar<Bar<T>>>` is `Foo`, and so on. This is
1353 clearly a recursive requirement that can't be resolved directly.
1355 Consider changing your trait bounds so that they're less self-referential.
1359 This error occurs when a bound in an implementation of a trait does not match
1360 the bounds specified in the original trait. For example:
1368 fn foo<T>(x: T) where T: Copy {}
1372 Here, all types implementing `Foo` must have a method `foo<T>(x: T)` which can
1373 take any type `T`. However, in the `impl` for `bool`, we have added an extra
1374 bound that `T` is `Copy`, which isn't compatible with the original trait.
1376 Consider removing the bound from the method or adding the bound to the original
1377 method definition in the trait.
1381 You tried to use a type which doesn't implement some trait in a place which
1382 expected that trait. Erroneous code example:
1385 // here we declare the Foo trait with a bar method
1390 // we now declare a function which takes an object implementing the Foo trait
1391 fn some_func<T: Foo>(foo: T) {
1396 // we now call the method with the i32 type, which doesn't implement
1398 some_func(5i32); // error: the trait `Foo` is not implemented for the
1403 In order to fix this error, verify that the type you're using does implement
1411 fn some_func<T: Foo>(foo: T) {
1412 foo.bar(); // we can now use this method since i32 implements the
1416 // we implement the trait on the i32 type
1422 some_func(5i32); // ok!
1428 You tried to supply a type which doesn't implement some trait in a location
1429 which expected that trait. This error typically occurs when working with
1430 `Fn`-based types. Erroneous code example:
1433 fn foo<F: Fn()>(x: F) { }
1436 // type mismatch: the type ... implements the trait `core::ops::Fn<(_,)>`,
1437 // but the trait `core::ops::Fn<()>` is required (expected (), found tuple
1443 The issue in this case is that `foo` is defined as accepting a `Fn` with no
1444 arguments, but the closure we attempted to pass to it requires one argument.
1448 This error indicates that type inference did not result in one unique possible
1449 type, and extra information is required. In most cases this can be provided
1450 by adding a type annotation. Sometimes you need to specify a generic type
1453 A common example is the `collect` method on `Iterator`. It has a generic type
1454 parameter with a `FromIterator` bound, which for a `char` iterator is
1455 implemented by `Vec` and `String` among others. Consider the following snippet
1456 that reverses the characters of a string:
1459 let x = "hello".chars().rev().collect();
1462 In this case, the compiler cannot infer what the type of `x` should be:
1463 `Vec<char>` and `String` are both suitable candidates. To specify which type to
1464 use, you can use a type annotation on `x`:
1467 let x: Vec<char> = "hello".chars().rev().collect();
1470 It is not necessary to annotate the full type. Once the ambiguity is resolved,
1471 the compiler can infer the rest:
1474 let x: Vec<_> = "hello".chars().rev().collect();
1477 Another way to provide the compiler with enough information, is to specify the
1478 generic type parameter:
1481 let x = "hello".chars().rev().collect::<Vec<char>>();
1484 Again, you need not specify the full type if the compiler can infer it:
1487 let x = "hello".chars().rev().collect::<Vec<_>>();
1490 Apart from a method or function with a generic type parameter, this error can
1491 occur when a type parameter of a struct or trait cannot be inferred. In that
1492 case it is not always possible to use a type annotation, because all candidates
1493 have the same return type. For instance:
1506 let number = Foo::bar();
1511 This will fail because the compiler does not know which instance of `Foo` to
1512 call `bar` on. Change `Foo::bar()` to `Foo::<T>::bar()` to resolve the error.
1516 This error occurs when the compiler doesn't have enough information
1517 to unambiguously choose an implementation.
1528 impl Generator for Impl {
1529 fn create() -> u32 { 1 }
1534 impl Generator for AnotherImpl {
1535 fn create() -> u32 { 2 }
1539 let cont: u32 = Generator::create();
1540 // error, impossible to choose one of Generator trait implementation
1541 // Impl or AnotherImpl? Maybe anything else?
1545 To resolve this error use the concrete type:
1554 impl Generator for AnotherImpl {
1555 fn create() -> u32 { 2 }
1559 let gen1 = AnotherImpl::create();
1561 // if there are multiple methods with same name (different traits)
1562 let gen2 = <AnotherImpl as Generator>::create();
1568 This error indicates that the given recursion limit could not be parsed. Ensure
1569 that the value provided is a positive integer between quotes, like so:
1572 #![recursion_limit="1000"]
1577 Patterns used to bind names must be irrefutable. That is, they must guarantee
1578 that a name will be extracted in all cases. Instead of pattern matching the
1579 loop variable, consider using a `match` or `if let` inside the loop body. For
1583 let xs : Vec<Option<i32>> = vec!(Some(1), None);
1585 // This fails because `None` is not covered.
1591 Match inside the loop instead:
1594 let xs : Vec<Option<i32>> = vec!(Some(1), None);
1607 let xs : Vec<Option<i32>> = vec!(Some(1), None);
1610 if let Some(x) = item {
1618 Mutable borrows are not allowed in pattern guards, because matching cannot have
1619 side effects. Side effects could alter the matched object or the environment
1620 on which the match depends in such a way, that the match would not be
1621 exhaustive. For instance, the following would not match any arm if mutable
1622 borrows were allowed:
1627 option if option.take().is_none() => {
1628 /* impossible, option is `Some` */
1630 Some(_) => { } // When the previous match failed, the option became `None`.
1636 Assignments are not allowed in pattern guards, because matching cannot have
1637 side effects. Side effects could alter the matched object or the environment
1638 on which the match depends in such a way, that the match would not be
1639 exhaustive. For instance, the following would not match any arm if assignments
1645 option if { option = None; false } { },
1646 Some(_) => { } // When the previous match failed, the option became `None`.
1652 In certain cases it is possible for sub-bindings to violate memory safety.
1653 Updates to the borrow checker in a future version of Rust may remove this
1654 restriction, but for now patterns must be rewritten without sub-bindings.
1658 match Some("hi".to_string()) {
1659 ref op_string_ref @ Some(s) => {},
1664 match Some("hi".to_string()) {
1666 let op_string_ref = &Some(s);
1673 The `op_string_ref` binding has type `&Option<&String>` in both cases.
1675 See also https://github.com/rust-lang/rust/issues/14587
1679 In an array literal `[x; N]`, `N` is the number of elements in the array. This
1680 must be an unsigned integer. Erroneous code example:
1683 let x = [0i32; true]; // error: expected positive integer for repeat count,
1695 The length of an array is part of its type. For this reason, this length must
1696 be a compile-time constant. Erroneous code example:
1700 let x = [0i32; len]; // error: expected constant integer for repeat count,
1706 This error occurs when the compiler was unable to infer the concrete type of a
1707 variable. It can occur for several cases, the most common of which is a
1708 mismatch in the expected type that the compiler inferred for a variable's
1709 initializing expression, and the actual type explicitly assigned to the
1715 let x: i32 = "I am not a number!";
1716 // ~~~ ~~~~~~~~~~~~~~~~~~~~
1718 // | initializing expression;
1719 // | compiler infers type `&str`
1721 // type `i32` assigned to variable `x`
1724 Another situation in which this occurs is when you attempt to use the `try!`
1725 macro inside a function that does not return a `Result<T, E>`:
1731 let mut f = try!(File::create("foo.txt"));
1735 This code gives an error like this:
1738 <std macros>:5:8: 6:42 error: mismatched types:
1740 found `core::result::Result<_, _>`
1742 found enum `core::result::Result`) [E0308]
1745 `try!` returns a `Result<T, E>`, and so the function must. But `main()` has
1746 `()` as its return type, hence the error.
1750 Types in type definitions have lifetimes associated with them that represent
1751 how long the data stored within them is guaranteed to be live. This lifetime
1752 must be as long as the data needs to be alive, and missing the constraint that
1753 denotes this will cause this error.
1756 // This won't compile because T is not constrained, meaning the data
1757 // stored in it is not guaranteed to last as long as the reference
1763 This will compile, because it has the constraint on the type parameter:
1766 struct Foo<'a, T: 'a> {
1773 Types in type definitions have lifetimes associated with them that represent
1774 how long the data stored within them is guaranteed to be live. This lifetime
1775 must be as long as the data needs to be alive, and missing the constraint that
1776 denotes this will cause this error.
1779 // This won't compile because T is not constrained to the static lifetime
1780 // the reference needs
1785 This will compile, because it has the constraint on the type parameter:
1788 struct Foo<T: 'static> {
1795 In Rust 1.3, the default object lifetime bounds are expected to change, as
1796 described in RFC #1156 [1]. You are getting a warning because the compiler
1797 thinks it is possible that this change will cause a compilation error in your
1798 code. It is possible, though unlikely, that this is a false alarm.
1800 The heart of the change is that where `&'a Box<SomeTrait>` used to default to
1801 `&'a Box<SomeTrait+'a>`, it now defaults to `&'a Box<SomeTrait+'static>` (here,
1802 `SomeTrait` is the name of some trait type). Note that the only types which are
1803 affected are references to boxes, like `&Box<SomeTrait>` or
1804 `&[Box<SomeTrait>]`. More common types like `&SomeTrait` or `Box<SomeTrait>`
1807 To silence this warning, edit your code to use an explicit bound. Most of the
1808 time, this means that you will want to change the signature of a function that
1809 you are calling. For example, if the error is reported on a call like `foo(x)`,
1810 and `foo` is defined as follows:
1813 fn foo(arg: &Box<SomeTrait>) { ... }
1816 You might change it to:
1819 fn foo<'a>(arg: &Box<SomeTrait+'a>) { ... }
1822 This explicitly states that you expect the trait object `SomeTrait` to contain
1823 references (with a maximum lifetime of `'a`).
1825 [1]: https://github.com/rust-lang/rfcs/pull/1156
1829 An invalid lint attribute has been given. Erroneous code example:
1832 #![allow(foo = "")] // error: malformed lint attribute
1835 Lint attributes only accept a list of identifiers (where each identifier is a
1836 lint name). Ensure the attribute is of this form:
1839 #![allow(foo)] // ok!
1841 #![allow(foo, foo2)] // ok!
1846 A lifetime name is shadowing another lifetime name. Erroneous code example:
1854 fn f<'a>(x: &'a i32) { // error: lifetime name `'a` shadows a lifetime
1855 // name that is already in scope
1860 Please change the name of one of the lifetimes to remove this error. Example:
1868 fn f<'b>(x: &'b i32) { // ok!
1878 A stability attribute was used outside of the standard library. Erroneous code
1882 #[stable] // error: stability attributes may not be used outside of the
1887 It is not possible to use stability attributes outside of the standard library.
1888 Also, for now, it is not possible to write deprecation messages either.
1892 This error indicates that a `#[repr(..)]` attribute was placed on an
1895 Examples of erroneous code:
1905 struct Foo {bar: bool, baz: bool}
1913 * The `#[repr(C)]` attribute can only be placed on structs and enums.
1914 * The `#[repr(packed)]` and `#[repr(simd)]` attributes only work on structs.
1915 * The `#[repr(u8)]`, `#[repr(i16)]`, etc attributes only work on enums.
1917 These attributes do not work on typedefs, since typedefs are just aliases.
1919 Representations like `#[repr(u8)]`, `#[repr(i64)]` are for selecting the
1920 discriminant size for C-like enums (when there is no associated data, e.g.
1921 `enum Color {Red, Blue, Green}`), effectively setting the size of the enum to
1922 the size of the provided type. Such an enum can be cast to a value of the same
1923 type as well. In short, `#[repr(u8)]` makes the enum behave like an integer
1924 with a constrained set of allowed values.
1926 Only C-like enums can be cast to numerical primitives, so this attribute will
1927 not apply to structs.
1929 `#[repr(packed)]` reduces padding to make the struct size smaller. The
1930 representation of enums isn't strictly defined in Rust, and this attribute
1931 won't work on enums.
1933 `#[repr(simd)]` will give a struct consisting of a homogenous series of machine
1934 types (i.e. `u8`, `i32`, etc) a representation that permits vectorization via
1935 SIMD. This doesn't make much sense for enums since they don't consist of a
1936 single list of data.
1940 This error indicates that an `#[inline(..)]` attribute was incorrectly placed
1941 on something other than a function or method.
1943 Examples of erroneous code:
1955 `#[inline]` hints the compiler whether or not to attempt to inline a method or
1956 function. By default, the compiler does a pretty good job of figuring this out
1957 itself, but if you feel the need for annotations, `#[inline(always)]` and
1958 `#[inline(never)]` can override or force the compiler's decision.
1960 If you wish to apply this attribute to all methods in an impl, manually annotate
1961 each method; it is not possible to annotate the entire impl with an `#[inline]`
1968 register_diagnostics! {
1969 // E0006 // merged with E0005
1972 E0278, // requirement is not satisfied
1973 E0279, // requirement is not satisfied
1974 E0280, // requirement is not satisfied
1975 E0284, // cannot resolve type
1976 // E0285, // overflow evaluation builtin bounds
1977 E0298, // mismatched types between arms
1978 E0299, // mismatched types between arms
1979 // E0300, // unexpanded macro
1980 // E0304, // expected signed integer constant
1981 // E0305, // expected constant
1982 E0311, // thing may not live long enough
1983 E0312, // lifetime of reference outlives lifetime of borrowed content
1984 E0313, // lifetime of borrowed pointer outlives lifetime of captured variable
1985 E0314, // closure outlives stack frame
1986 E0315, // cannot invoke closure outside of its lifetime
1987 E0316, // nested quantification of lifetimes
1988 E0453, // overruled by outer forbid
1989 E0471, // constant evaluation error: ..
1990 E0473, // dereference of reference outside its lifetime
1991 E0474, // captured variable `..` does not outlive the enclosing closure
1992 E0475, // index of slice outside its lifetime
1993 E0476, // lifetime of the source pointer does not outlive lifetime bound...
1994 E0477, // the type `..` does not fulfill the required lifetime...
1995 E0478, // lifetime bound not satisfied
1996 E0479, // the type `..` (provided as the value of a type parameter) is...
1997 E0480, // lifetime of method receiver does not outlive the method call
1998 E0481, // lifetime of function argument does not outlive the function call
1999 E0482, // lifetime of return value does not outlive the function call
2000 E0483, // lifetime of operand does not outlive the operation
2001 E0484, // reference is not valid at the time of borrow
2002 E0485, // automatically reference is not valid at the time of borrow
2003 E0486, // type of expression contains references that are not valid during...
2004 E0487, // unsafe use of destructor: destructor might be called while...
2005 E0488, // lifetime of variable does not enclose its declaration
2006 E0489, // type/lifetime parameter not in scope here
2007 E0490, // a value of type `..` is borrowed for too long
2008 E0491, // in type `..`, reference has a longer lifetime than the data it...
2009 E0495, // cannot infer an appropriate lifetime due to conflicting requirements