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 one
24 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.
109 If you encounter this error you must alter your patterns so that every possible
110 value of the input type is matched. For types with a small number of variants
111 (like enums) you should probably cover all cases explicitly. Alternatively, the
112 underscore `_` wildcard pattern can be added after all other patterns to match
117 Patterns used to bind names must be irrefutable, that is, they must guarantee
118 that a name will be extracted in all cases. If you encounter this error you
119 probably need to use a `match` or `if let` to deal with the possibility of
124 This error indicates that the bindings in a match arm would require a value to
125 be moved into more than one location, thus violating unique ownership. Code like
126 the following is invalid as it requires the entire `Option<String>` to be moved
127 into a variable called `op_string` while simultaneously requiring the inner
128 String to be moved into a variable called `s`.
131 let x = Some("s".to_string());
134 op_string @ Some(s) => {},
139 See also the error E0303.
143 Names bound in match arms retain their type in pattern guards. As such, if a
144 name is bound by move in a pattern, it should also be moved to wherever it is
145 referenced in the pattern guard code. Doing so however would prevent the name
146 from being available in the body of the match arm. Consider the following:
149 match Some("hi".to_string()) {
150 Some(s) if s.len() == 0 => {}, // use s.
155 The variable `s` has type `String`, and its use in the guard is as a variable of
156 type `String`. The guard code effectively executes in a separate scope to the
157 body of the arm, so the value would be moved into this anonymous scope and
158 therefore become unavailable in the body of the arm. Although this example seems
159 innocuous, the problem is most clear when considering functions that take their
163 match Some("hi".to_string()) {
164 Some(s) if { drop(s); false } => (),
165 Some(s) => {}, // use s.
170 The value would be dropped in the guard then become unavailable not only in the
171 body of that arm but also in all subsequent arms! The solution is to bind by
172 reference when using guards or refactor the entire expression, perhaps by
173 putting the condition inside the body of the arm.
177 In a pattern, all values that don't implement the `Copy` trait have to be bound
178 the same way. The goal here is to avoid binding simultaneously by-move and
181 This limitation may be removed in a future version of Rust.
188 let x = Some((X { x: () }, X { x: () }));
190 Some((y, ref z)) => {},
195 You have two solutions:
197 Solution #1: Bind the pattern's values the same way.
202 let x = Some((X { x: () }, X { x: () }));
204 Some((ref y, ref z)) => {},
205 // or Some((y, z)) => {}
210 Solution #2: Implement the `Copy` trait for the `X` structure.
212 However, please keep in mind that the first solution should be preferred.
215 #[derive(Clone, Copy)]
218 let x = Some((X { x: () }, X { x: () }));
220 Some((y, ref z)) => {},
227 This error indicates that an attempt was made to divide by zero (or take the
228 remainder of a zero divisor) in a static or constant expression. Erroneous
232 const X: i32 = 42 / 0;
233 // error: attempted to divide by zero in a constant expression
238 Trait objects like `Box<Trait>` can only be constructed when certain
239 requirements are satisfied by the trait in question.
241 Trait objects are a form of dynamic dispatch and use a dynamically sized type
242 for the inner type. So, for a given trait `Trait`, when `Trait` is treated as a
243 type, as in `Box<Trait>`, the inner type is 'unsized'. In such cases the boxed
244 pointer is a 'fat pointer' that contains an extra pointer to a table of methods
245 (among other things) for dynamic dispatch. This design mandates some
246 restrictions on the types of traits that are allowed to be used in trait
247 objects, which are collectively termed as 'object safety' rules.
249 Attempting to create a trait object for a non object-safe trait will trigger
252 There are various rules:
254 ### The trait cannot require `Self: Sized`
256 When `Trait` is treated as a type, the type does not implement the special
257 `Sized` trait, because the type does not have a known size at compile time and
258 can only be accessed behind a pointer. Thus, if we have a trait like the
262 trait Foo where Self: Sized {
267 we cannot create an object of type `Box<Foo>` or `&Foo` since in this case
268 `Self` would not be `Sized`.
270 Generally, `Self : Sized` is used to indicate that the trait should not be used
271 as a trait object. If the trait comes from your own crate, consider removing
274 ### Method references the `Self` type in its arguments or return type
276 This happens when a trait has a method like the following:
280 fn foo(&self) -> Self;
283 impl Trait for String {
284 fn foo(&self) -> Self {
290 fn foo(&self) -> Self {
296 (Note that `&self` and `&mut self` are okay, it's additional `Self` types which
299 In such a case, the compiler cannot predict the return type of `foo()` in a
300 situation like the following:
304 fn foo(&self) -> Self;
307 fn call_foo(x: Box<Trait>) {
308 let y = x.foo(); // What type is y?
313 If only some methods aren't object-safe, you can add a `where Self: Sized` bound
314 on them to mark them as explicitly unavailable to trait objects. The
315 functionality will still be available to all other implementers, including
316 `Box<Trait>` which is itself sized (assuming you `impl Trait for Box<Trait>`).
320 fn foo(&self) -> Self where Self: Sized;
325 Now, `foo()` can no longer be called on a trait object, but you will now be
326 allowed to make a trait object, and that will be able to call any object-safe
327 methods". With such a bound, one can still call `foo()` on types implementing
328 that trait that aren't behind trait objects.
330 ### Method has generic type parameters
332 As mentioned before, trait objects contain pointers to method tables. So, if we
340 impl Trait for String {
354 At compile time each implementation of `Trait` will produce a table containing
355 the various methods (and other items) related to the implementation.
357 This works fine, but when the method gains generic parameters, we can have a
360 Usually, generic parameters get _monomorphized_. For example, if I have
368 The machine code for `foo::<u8>()`, `foo::<bool>()`, `foo::<String>()`, or any
369 other type substitution is different. Hence the compiler generates the
370 implementation on-demand. If you call `foo()` with a `bool` parameter, the
371 compiler will only generate code for `foo::<bool>()`. When we have additional
372 type parameters, the number of monomorphized implementations the compiler
373 generates does not grow drastically, since the compiler will only generate an
374 implementation if the function is called with unparametrized substitutions
375 (i.e., substitutions where none of the substituted types are themselves
378 However, with trait objects we have to make a table containing _every_ object
379 that implements the trait. Now, if it has type parameters, we need to add
380 implementations for every type that implements the trait, and there could
381 theoretically be an infinite number of types.
387 fn foo<T>(&self, on: T);
391 impl Trait for String {
392 fn foo<T>(&self, on: T) {
398 fn foo<T>(&self, on: T) {
403 // 8 more implementations
406 Now, if we have the following code:
409 fn call_foo(thing: Box<Trait>) {
410 thing.foo(true); // this could be any one of the 8 types above
416 We don't just need to create a table of all implementations of all methods of
417 `Trait`, we need to create such a table, for each different type fed to
418 `foo()`. In this case this turns out to be (10 types implementing `Trait`)*(3
419 types being fed to `foo()`) = 30 implementations!
421 With real world traits these numbers can grow drastically.
423 To fix this, it is suggested to use a `where Self: Sized` bound similar to the
424 fix for the sub-error above if you do not intend to call the method with type
429 fn foo<T>(&self, on: T) where Self: Sized;
434 If this is not an option, consider replacing the type parameter with another
435 trait object (e.g. if `T: OtherTrait`, use `on: Box<OtherTrait>`). If the number
436 of types you intend to feed to this method is limited, consider manually listing
437 out the methods of different types.
439 ### Method has no receiver
441 Methods that do not take a `self` parameter can't be called since there won't be
442 a way to get a pointer to the method table for them.
450 This could be called as `<Foo as Foo>::foo()`, which would not be able to pick
453 Adding a `Self: Sized` bound to these methods will generally make this compile.
457 fn foo() -> u8 where Self: Sized;
461 ### The trait cannot use `Self` as a type parameter in the supertrait listing
463 This is similar to the second sub-error, but subtler. It happens in situations
469 trait Trait: Super<Self> {
474 impl Super<Foo> for Foo{}
476 impl Trait for Foo {}
479 Here, the supertrait might have methods as follows:
483 fn get_a(&self) -> A; // note that this is object safe!
487 If the trait `Foo` was deriving from something like `Super<String>` or
488 `Super<T>` (where `Foo` itself is `Foo<T>`), this is okay, because given a type
489 `get_a()` will definitely return an object of that type.
491 However, if it derives from `Super<Self>`, even though `Super` is object safe,
492 the method `get_a()` would return an object of unknown type when called on the
493 function. `Self` type parameters let us make object safe traits no longer safe,
494 so they are forbidden when specifying supertraits.
496 There's no easy fix for this, generally code will need to be refactored so that
497 you no longer need to derive from `Super<Self>`.
501 When defining a recursive struct or enum, any use of the type being defined
502 from inside the definition must occur behind a pointer (like `Box` or `&`).
503 This is because structs and enums must have a well-defined size, and without
504 the pointer the size of the type would need to be unbounded.
506 Consider the following erroneous definition of a type for a list of bytes:
509 // error, invalid recursive struct type
512 tail: Option<ListNode>,
516 This type cannot have a well-defined size, because it needs to be arbitrarily
517 large (since we would be able to nest `ListNode`s to any depth). Specifically,
520 size of `ListNode` = 1 byte for `head`
521 + 1 byte for the discriminant of the `Option`
525 One way to fix this is by wrapping `ListNode` in a `Box`, like so:
530 tail: Option<Box<ListNode>>,
534 This works because `Box` is a pointer, so its size is well-known.
538 You tried to give a type parameter to a type which doesn't need it. Erroneous
542 type X = u32<i32>; // error: type parameters are not allowed on this type
545 Please check that you used the correct type and recheck its definition. Perhaps
546 it doesn't need the type parameter.
551 type X = u32; // this compiles
554 Note that type parameters for enum-variant constructors go after the variant,
555 not after the enum (Option::None::<u32>, not Option::<u32>::None).
559 You tried to give a lifetime parameter to a type which doesn't need it.
560 Erroneous code example:
563 type X = u32<'static>; // error: lifetime parameters are not allowed on
567 Please check that the correct type was used and recheck its definition; perhaps
568 it doesn't need the lifetime parameter. Example:
576 Using unsafe functionality, is potentially dangerous and disallowed
577 by safety checks. Examples:
579 - Dereferencing raw pointers
580 - Calling functions via FFI
581 - Calling functions marked unsafe
583 These safety checks can be relaxed for a section of the code
584 by wrapping the unsafe instructions with an `unsafe` block. For instance:
587 unsafe fn f() { return; }
594 See also https://doc.rust-lang.org/book/unsafe.html
597 // This shouldn't really ever trigger since the repeated value error comes first
599 A binary can only have one entry point, and by default that entry point is the
600 function `main()`. If there are multiple such functions, please rename one.
604 This error indicates that the compiler found multiple functions with the
605 `#[main]` attribute. This is an error because there must be a unique entry
606 point into a Rust program.
610 This error indicates that the compiler found multiple functions with the
611 `#[start]` attribute. This is an error because there must be a unique entry
612 point into a Rust program.
615 // FIXME link this to the relevant turpl chapters for instilling fear of the
616 // transmute gods in the user
618 There are various restrictions on transmuting between types in Rust; for example
619 types being transmuted must have the same size. To apply all these restrictions,
620 the compiler must know the exact types that may be transmuted. When type
621 parameters are involved, this cannot always be done.
623 So, for example, the following is not allowed:
626 struct Foo<T>(Vec<T>);
628 fn foo<T>(x: Vec<T>) {
629 // we are transmuting between Vec<T> and Foo<T> here
630 let y: Foo<T> = unsafe { transmute(x) };
631 // do something with y
635 In this specific case there's a good chance that the transmute is harmless (but
636 this is not guaranteed by Rust). However, when alignment and enum optimizations
637 come into the picture, it's quite likely that the sizes may or may not match
638 with different type parameter substitutions. It's not possible to check this for
639 _all_ possible types, so `transmute()` simply only accepts types without any
640 unsubstituted type parameters.
642 If you need this, there's a good chance you're doing something wrong. Keep in
643 mind that Rust doesn't guarantee much about the layout of different structs
644 (even two structs with identical declarations may have different layouts). If
645 there is a solution that avoids the transmute entirely, try it instead.
647 If it's possible, hand-monomorphize the code by writing the function for each
648 possible type substitution. It's possible to use traits to do this cleanly,
652 struct Foo<T>(Vec<T>);
654 trait MyTransmutableType {
655 fn transmute(Vec<Self>) -> Foo<Self>;
658 impl MyTransmutableType for u8 {
659 fn transmute(x: Foo<u8>) -> Vec<u8> {
664 impl MyTransmutableType for String {
665 fn transmute(x: Foo<String>) -> Vec<String> {
670 // ... more impls for the types you intend to transmute
672 fn foo<T: MyTransmutableType>(x: Vec<T>) {
673 let y: Foo<T> = <T as MyTransmutableType>::transmute(x);
674 // do something with y
678 Each impl will be checked for a size match in the transmute as usual, and since
679 there are no unbound type parameters involved, this should compile unless there
680 is a size mismatch in one of the impls.
682 It is also possible to manually transmute:
685 ptr::read(&v as *const _ as *const SomeType) // `v` transmuted to `SomeType`
688 Note that this does not move `v` (unlike `transmute`), and may need a
689 call to `mem::forget(v)` in case you want to avoid destructors being called.
693 Lang items are already implemented in the standard library. Unless you are
694 writing a free-standing application (e.g. a kernel), you do not need to provide
697 You can build a free-standing crate by adding `#![no_std]` to the crate
704 See also https://doc.rust-lang.org/book/no-stdlib.html
708 `const` and `static` mean different things. A `const` is a compile-time
709 constant, an alias for a literal value. This property means you can match it
710 directly within a pattern.
712 The `static` keyword, on the other hand, guarantees a fixed location in memory.
713 This does not always mean that the value is constant. For example, a global
714 mutex can be declared `static` as well.
716 If you want to match against a `static`, consider using a guard instead:
719 static FORTY_TWO: i32 = 42;
722 Some(x) if x == FORTY_TWO => {}
729 An if-let pattern attempts to match the pattern, and enters the body if the
730 match was successful. If the match is irrefutable (when it cannot fail to
731 match), use a regular `let`-binding instead. For instance:
734 struct Irrefutable(i32);
735 let irr = Irrefutable(0);
737 // This fails to compile because the match is irrefutable.
738 if let Irrefutable(x) = irr {
739 // This body will always be executed.
747 struct Irrefutable(i32);
748 let irr = Irrefutable(0);
750 let Irrefutable(x) = irr;
756 A while-let pattern attempts to match the pattern, and enters the body if the
757 match was successful. If the match is irrefutable (when it cannot fail to
758 match), use a regular `let`-binding inside a `loop` instead. For instance:
761 struct Irrefutable(i32);
762 let irr = Irrefutable(0);
764 // This fails to compile because the match is irrefutable.
765 while let Irrefutable(x) = irr {
772 struct Irrefutable(i32);
773 let irr = Irrefutable(0);
776 let Irrefutable(x) = irr;
783 Enum variants are qualified by default. For example, given this type:
792 You would match it using:
808 If you don't qualify the names, the code will bind new variables named "GET" and
809 "POST" instead. This behavior is likely not what you want, so `rustc` warns when
812 Qualified names are good practice, and most code works well with them. But if
813 you prefer them unqualified, you can import the variants into scope:
817 enum Method { GET, POST }
820 If you want others to be able to import variants from your module directly, use
825 enum Method { GET, POST }
830 An associated type binding was done outside of the type parameter declaration
831 and `where` clause. Erroneous code example:
836 fn boo(&self) -> <Self as Foo>::A;
843 fn boo(&self) -> usize { 42 }
846 fn baz<I>(x: &<I as Foo<A=Bar>>::A) {}
847 // error: associated type bindings are not allowed here
850 To solve this error, please move the type bindings in the type parameter
854 fn baz<I: Foo<A=Bar>>(x: &<I as Foo>::A) {} // ok!
857 Or in the `where` clause:
860 fn baz<I>(x: &<I as Foo>::A) where I: Foo<A=Bar> {}
865 When using a lifetime like `'a` in a type, it must be declared before being
868 These two examples illustrate the problem:
871 // error, use of undeclared lifetime name `'a`
872 fn foo(x: &'a str) { }
875 // error, use of undeclared lifetime name `'a`
880 These can be fixed by declaring lifetime parameters:
883 fn foo<'a>(x: &'a str) {}
892 Declaring certain lifetime names in parameters is disallowed. For example,
893 because the `'static` lifetime is a special built-in lifetime name denoting
894 the lifetime of the entire program, this is an error:
897 // error, invalid lifetime parameter name `'static`
898 fn foo<'static>(x: &'static str) { }
903 A lifetime name cannot be declared more than once in the same scope. For
907 // error, lifetime name `'a` declared twice in the same scope
908 fn foo<'a, 'b, 'a>(x: &'a str, y: &'b str) { }
913 An unknown external lang item was used. Erroneous code example:
916 #![feature(lang_items)]
919 #[lang = "cake"] // error: unknown external lang item: `cake`
924 A list of available external lang items is available in
925 `src/librustc/middle/weak_lang_items.rs`. Example:
928 #![feature(lang_items)]
931 #[lang = "panic_fmt"] // ok!
938 Functions must eventually return a value of their return type. For example, in
939 the following function:
942 fn foo(x: u8) -> u8 {
944 x // alternatively, `return x`
950 If the condition is true, the value `x` is returned, but if the condition is
951 false, control exits the `if` block and reaches a place where nothing is being
952 returned. All possible control paths must eventually return a `u8`, which is not
955 An easy fix for this in a complicated function is to specify a default return
959 fn foo(x: u8) -> u8 {
961 x // alternatively, `return x`
963 // lots of other if branches
964 0 // return 0 if all else fails
968 It is advisable to find out what the unhandled cases are and check for them,
969 returning an appropriate value or panicking if necessary.
973 Rust lets you define functions which are known to never return, i.e. are
974 'diverging', by marking its return type as `!`.
976 For example, the following functions never return:
984 foo() // foo() is diverging, so this will diverge too
988 panic!(); // this macro internally expands to a call to a diverging function
992 Such functions can be used in a place where a value is expected without
993 returning a value of that type, for instance:
1005 _ => foo() // diverging function called here
1011 If the third arm of the match block is reached, since `foo()` doesn't ever
1012 return control to the match block, it is fine to use it in a place where an
1013 integer was expected. The `match` block will never finish executing, and any
1014 point where `y` (like the print statement) is needed will not be reached.
1016 However, if we had a diverging function that actually does finish execution:
1024 Then we would have an unknown value for `y` in the following code:
1042 In the previous example, the print statement was never reached when the wildcard
1043 match arm was hit, so we were okay with `foo()` not returning an integer that we
1044 could set to `y`. But in this example, `foo()` actually does return control, so
1045 the print statement will be executed with an uninitialized value.
1047 Obviously we cannot have functions which are allowed to be used in such
1048 positions and yet can return control. So, if you are defining a function that
1049 returns `!`, make sure that there is no way for it to actually finish executing.
1053 This is because of a type mismatch between the associated type of some
1054 trait (e.g. `T::Bar`, where `T` implements `trait Quux { type Bar; }`)
1055 and another type `U` that is required to be equal to `T::Bar`, but is not.
1058 Here is a basic example:
1061 trait Trait { type AssociatedType; }
1063 fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
1067 impl Trait for i8 { type AssociatedType = &'static str; }
1072 Here is that same example again, with some explanatory comments:
1075 trait Trait { type AssociatedType; }
1077 fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
1078 // ~~~~~~~~ ~~~~~~~~~~~~~~~~~~
1080 // This says `foo` can |
1081 // only be used with |
1083 // implements `Trait`. |
1085 // This says not only must
1086 // `T` be an impl of `Trait`
1087 // but also that the impl
1088 // must assign the type `u32`
1089 // to the associated type.
1093 impl Trait for i8 { type AssociatedType = &'static str; }
1094 ~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1099 // ... but it is an implementation
1100 // that assigns `&'static str` to
1101 // the associated type.
1104 // Here, we invoke `foo` with an `i8`, which does not satisfy
1105 // the constraint `<i8 as Trait>::AssociatedType=u32`, and
1106 // therefore the type-checker complains with this error code.
1109 Here is a more subtle instance of the same problem, that can
1110 arise with for-loops in Rust:
1113 let vs: Vec<i32> = vec![1, 2, 3, 4];
1122 The above fails because of an analogous type mismatch,
1123 though may be harder to see. Again, here are some
1124 explanatory comments for the same example:
1128 let vs = vec![1, 2, 3, 4];
1130 // `for`-loops use a protocol based on the `Iterator`
1131 // trait. Each item yielded in a `for` loop has the
1132 // type `Iterator::Item` -- that is, `Item` is the
1133 // associated type of the concrete iterator impl.
1137 // | We borrow `vs`, iterating over a sequence of
1138 // | *references* of type `&Elem` (where `Elem` is
1139 // | vector's element type). Thus, the associated
1140 // | type `Item` must be a reference `&`-type ...
1142 // ... and `v` has the type `Iterator::Item`, as dictated by
1143 // the `for`-loop protocol ...
1149 // ... but *here*, `v` is forced to have some integral type;
1150 // only types like `u8`,`i8`,`u16`,`i16`, et cetera can
1151 // match the pattern `1` ...
1156 // ... therefore, the compiler complains, because it sees
1157 // an attempt to solve the equations
1158 // `some integral-type` = type-of-`v`
1159 // = `Iterator::Item`
1160 // = `&Elem` (i.e. `some reference type`)
1162 // which cannot possibly all be true.
1168 To avoid those issues, you have to make the types match correctly.
1169 So we can fix the previous examples like this:
1173 trait Trait { type AssociatedType; }
1175 fn foo<T>(t: T) where T: Trait<AssociatedType = &'static str> {
1179 impl Trait for i8 { type AssociatedType = &'static str; }
1183 // For-Loop Example:
1184 let vs = vec![1, 2, 3, 4];
1195 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
1196 message for when a particular trait isn't implemented on a type placed in a
1197 position that needs that trait. For example, when the following code is
1201 fn foo<T: Index<u8>>(x: T){}
1203 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1204 trait Index<Idx> { ... }
1206 foo(true); // `bool` does not implement `Index<u8>`
1209 there will be an error about `bool` not implementing `Index<u8>`, followed by a
1210 note saying "the type `bool` cannot be indexed by `u8`".
1212 As you can see, you can specify type parameters in curly braces for substitution
1213 with the actual types (using the regular format string syntax) in a given
1214 situation. Furthermore, `{Self}` will substitute to the type (in this case,
1215 `bool`) that we tried to use.
1217 This error appears when the curly braces contain an identifier which doesn't
1218 match with any of the type parameters or the string `Self`. This might happen if
1219 you misspelled a type parameter, or if you intended to use literal curly braces.
1220 If it is the latter, escape the curly braces with a second curly brace of the
1221 same type; e.g. a literal `{` is `{{`
1225 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
1226 message for when a particular trait isn't implemented on a type placed in a
1227 position that needs that trait. For example, when the following code is
1231 fn foo<T: Index<u8>>(x: T){}
1233 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1234 trait Index<Idx> { ... }
1236 foo(true); // `bool` does not implement `Index<u8>`
1239 there will be an error about `bool` not implementing `Index<u8>`, followed by a
1240 note saying "the type `bool` cannot be indexed by `u8`".
1242 As you can see, you can specify type parameters in curly braces for substitution
1243 with the actual types (using the regular format string syntax) in a given
1244 situation. Furthermore, `{Self}` will substitute to the type (in this case,
1245 `bool`) that we tried to use.
1247 This error appears when the curly braces do not contain an identifier. Please
1248 add one of the same name as a type parameter. If you intended to use literal
1249 braces, use `{{` and `}}` to escape them.
1253 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
1254 message for when a particular trait isn't implemented on a type placed in a
1255 position that needs that trait. For example, when the following code is
1259 fn foo<T: Index<u8>>(x: T){}
1261 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1262 trait Index<Idx> { ... }
1264 foo(true); // `bool` does not implement `Index<u8>`
1267 there will be an error about `bool` not implementing `Index<u8>`, followed by a
1268 note saying "the type `bool` cannot be indexed by `u8`".
1270 For this to work, some note must be specified. An empty attribute will not do
1271 anything, please remove the attribute or add some helpful note for users of the
1276 This error occurs when there was a recursive trait requirement that overflowed
1277 before it could be evaluated. Often this means that there is unbounded recursion
1278 in resolving some type bounds.
1280 For example, in the following code:
1287 impl<T> Foo for T where Bar<T>: Foo {}
1290 To determine if a `T` is `Foo`, we need to check if `Bar<T>` is `Foo`. However,
1291 to do this check, we need to determine that `Bar<Bar<T>>` is `Foo`. To determine
1292 this, we check if `Bar<Bar<Bar<T>>>` is `Foo`, and so on. This is clearly a
1293 recursive requirement that can't be resolved directly.
1295 Consider changing your trait bounds so that they're less self-referential.
1299 This error occurs when a bound in an implementation of a trait does not match
1300 the bounds specified in the original trait. For example:
1308 fn foo<T>(x: T) where T: Copy {}
1312 Here, all types implementing `Foo` must have a method `foo<T>(x: T)` which can
1313 take any type `T`. However, in the `impl` for `bool`, we have added an extra
1314 bound that `T` is `Copy`, which isn't compatible with the original trait.
1316 Consider removing the bound from the method or adding the bound to the original
1317 method definition in the trait.
1321 You tried to use a type which doesn't implement some trait in a place which
1322 expected that trait. Erroneous code example:
1325 // here we declare the Foo trait with a bar method
1330 // we now declare a function which takes an object implementing the Foo trait
1331 fn some_func<T: Foo>(foo: T) {
1336 // we now call the method with the i32 type, which doesn't implement
1338 some_func(5i32); // error: the trait `Foo` is not implemented for the
1343 In order to fix this error, verify that the type you're using does implement
1351 fn some_func<T: Foo>(foo: T) {
1352 foo.bar(); // we can now use this method since i32 implements the
1356 // we implement the trait on the i32 type
1362 some_func(5i32); // ok!
1368 You tried to supply a type which doesn't implement some trait in a location
1369 which expected that trait. This error typically occurs when working with
1370 `Fn`-based types. Erroneous code example:
1373 fn foo<F: Fn()>(x: F) { }
1376 // type mismatch: the type ... implements the trait `core::ops::Fn<(_,)>`,
1377 // but the trait `core::ops::Fn<()>` is required (expected (), found tuple
1383 The issue in this case is that `foo` is defined as accepting a `Fn` with no
1384 arguments, but the closure we attempted to pass to it requires one argument.
1388 This error indicates that type inference did not result in one unique possible
1389 type, and extra information is required. In most cases this can be provided
1390 by adding a type annotation. Sometimes you need to specify a generic type
1393 A common example is the `collect` method on `Iterator`. It has a generic type
1394 parameter with a `FromIterator` bound, which for a `char` iterator is
1395 implemented by `Vec` and `String` among others. Consider the following snippet
1396 that reverses the characters of a string:
1399 let x = "hello".chars().rev().collect();
1402 In this case, the compiler cannot infer what the type of `x` should be:
1403 `Vec<char>` and `String` are both suitable candidates. To specify which type to
1404 use, you can use a type annotation on `x`:
1407 let x: Vec<char> = "hello".chars().rev().collect();
1410 It is not necessary to annotate the full type. Once the ambiguity is resolved,
1411 the compiler can infer the rest:
1414 let x: Vec<_> = "hello".chars().rev().collect();
1417 Another way to provide the compiler with enough information, is to specify the
1418 generic type parameter:
1421 let x = "hello".chars().rev().collect::<Vec<char>>();
1424 Again, you need not specify the full type if the compiler can infer it:
1427 let x = "hello".chars().rev().collect::<Vec<_>>();
1430 Apart from a method or function with a generic type parameter, this error can
1431 occur when a type parameter of a struct or trait cannot be inferred. In that
1432 case it is not always possible to use a type annotation, because all candidates
1433 have the same return type. For instance:
1446 let number = Foo::bar();
1451 This will fail because the compiler does not know which instance of `Foo` to
1452 call `bar` on. Change `Foo::bar()` to `Foo::<T>::bar()` to resolve the error.
1456 This error occurs when the compiler doesn't have enough information
1457 to unambiguously choose an implementation.
1468 impl Generator for Impl {
1469 fn create() -> u32 { 1 }
1474 impl Generator for AnotherImpl {
1475 fn create() -> u32 { 2 }
1479 let cont: u32 = Generator::create();
1480 // error, impossible to choose one of Generator trait implementation
1481 // Impl or AnotherImpl? Maybe anything else?
1485 To resolve this error use the concrete type:
1494 impl Generator for AnotherImpl {
1495 fn create() -> u32 { 2 }
1499 let gen1 = AnotherImpl::create();
1501 // if there are multiple methods with same name (different traits)
1502 let gen2 = <AnotherImpl as Generator>::create();
1508 This error indicates that the given recursion limit could not be parsed. Ensure
1509 that the value provided is a positive integer between quotes, like so:
1512 #![recursion_limit="1000"]
1517 Patterns used to bind names must be irrefutable. That is, they must guarantee
1518 that a name will be extracted in all cases. Instead of pattern matching the
1519 loop variable, consider using a `match` or `if let` inside the loop body. For
1523 let xs : Vec<Option<i32>> = vec!(Some(1), None);
1525 // This fails because `None` is not covered.
1531 Match inside the loop instead:
1534 let xs : Vec<Option<i32>> = vec!(Some(1), None);
1547 let xs : Vec<Option<i32>> = vec!(Some(1), None);
1550 if let Some(x) = item {
1558 Mutable borrows are not allowed in pattern guards, because matching cannot have
1559 side effects. Side effects could alter the matched object or the environment
1560 on which the match depends in such a way, that the match would not be
1561 exhaustive. For instance, the following would not match any arm if mutable
1562 borrows were allowed:
1567 option if option.take().is_none() => { /* impossible, option is `Some` */ },
1568 Some(_) => { } // When the previous match failed, the option became `None`.
1574 Assignments are not allowed in pattern guards, because matching cannot have
1575 side effects. Side effects could alter the matched object or the environment
1576 on which the match depends in such a way, that the match would not be
1577 exhaustive. For instance, the following would not match any arm if assignments
1583 option if { option = None; false } { },
1584 Some(_) => { } // When the previous match failed, the option became `None`.
1590 In certain cases it is possible for sub-bindings to violate memory safety.
1591 Updates to the borrow checker in a future version of Rust may remove this
1592 restriction, but for now patterns must be rewritten without sub-bindings.
1596 match Some("hi".to_string()) {
1597 ref op_string_ref @ Some(s) => {},
1602 match Some("hi".to_string()) {
1604 let op_string_ref = &Some(s);
1611 The `op_string_ref` binding has type `&Option<&String>` in both cases.
1613 See also https://github.com/rust-lang/rust/issues/14587
1617 In an array literal `[x; N]`, `N` is the number of elements in the array. This
1618 number cannot be negative.
1622 The length of an array is part of its type. For this reason, this length must be
1623 a compile-time constant.
1627 This error occurs when the compiler was unable to infer the concrete type of a
1628 variable. It can occur for several cases, the most common of which is a
1629 mismatch in the expected type that the compiler inferred for a variable's
1630 initializing expression, and the actual type explicitly assigned to the
1636 let x: i32 = "I am not a number!";
1637 // ~~~ ~~~~~~~~~~~~~~~~~~~~
1639 // | initializing expression;
1640 // | compiler infers type `&str`
1642 // type `i32` assigned to variable `x`
1645 Another situation in which this occurs is when you attempt to use the `try!`
1646 macro inside a function that does not return a `Result<T, E>`:
1652 let mut f = try!(File::create("foo.txt"));
1656 This code gives an error like this:
1659 <std macros>:5:8: 6:42 error: mismatched types:
1661 found `core::result::Result<_, _>`
1663 found enum `core::result::Result`) [E0308]
1666 `try!` returns a `Result<T, E>`, and so the function must. But `main()` has
1667 `()` as its return type, hence the error.
1671 Types in type definitions have lifetimes associated with them that represent
1672 how long the data stored within them is guaranteed to be live. This lifetime
1673 must be as long as the data needs to be alive, and missing the constraint that
1674 denotes this will cause this error.
1677 // This won't compile because T is not constrained, meaning the data
1678 // stored in it is not guaranteed to last as long as the reference
1684 This will compile, because it has the constraint on the type parameter:
1687 struct Foo<'a, T: 'a> {
1694 Types in type definitions have lifetimes associated with them that represent
1695 how long the data stored within them is guaranteed to be live. This lifetime
1696 must be as long as the data needs to be alive, and missing the constraint that
1697 denotes this will cause this error.
1700 // This won't compile because T is not constrained to the static lifetime
1701 // the reference needs
1706 This will compile, because it has the constraint on the type parameter:
1709 struct Foo<T: 'static> {
1716 In Rust 1.3, the default object lifetime bounds are expected to
1717 change, as described in RFC #1156 [1]. You are getting a warning
1718 because the compiler thinks it is possible that this change will cause
1719 a compilation error in your code. It is possible, though unlikely,
1720 that this is a false alarm.
1722 The heart of the change is that where `&'a Box<SomeTrait>` used to
1723 default to `&'a Box<SomeTrait+'a>`, it now defaults to `&'a
1724 Box<SomeTrait+'static>` (here, `SomeTrait` is the name of some trait
1725 type). Note that the only types which are affected are references to
1726 boxes, like `&Box<SomeTrait>` or `&[Box<SomeTrait>]`. More common
1727 types like `&SomeTrait` or `Box<SomeTrait>` are unaffected.
1729 To silence this warning, edit your code to use an explicit bound.
1730 Most of the time, this means that you will want to change the
1731 signature of a function that you are calling. For example, if
1732 the error is reported on a call like `foo(x)`, and `foo` is
1736 fn foo(arg: &Box<SomeTrait>) { ... }
1739 You might change it to:
1742 fn foo<'a>(arg: &Box<SomeTrait+'a>) { ... }
1745 This explicitly states that you expect the trait object `SomeTrait` to
1746 contain references (with a maximum lifetime of `'a`).
1748 [1]: https://github.com/rust-lang/rfcs/pull/1156
1752 An invalid lint attribute has been given. Erroneous code example:
1755 #![allow(foo = "")] // error: malformed lint attribute
1758 Lint attributes only accept a list of identifiers (where each identifier is a
1759 lint name). Ensure the attribute is of this form:
1762 #![allow(foo)] // ok!
1764 #![allow(foo, foo2)] // ok!
1769 A lifetime name is shadowing another lifetime name. Erroneous code example:
1777 fn f<'a>(x: &'a i32) { // error: lifetime name `'a` shadows a lifetime
1778 // name that is already in scope
1783 Please change the name of one of the lifetimes to remove this error. Example:
1791 fn f<'b>(x: &'b i32) { // ok!
1801 A stability attribute was used outside of the standard library. Erroneous code
1805 #[stable] // error: stability attributes may not be used outside of the
1810 It is not possible to use stability attributes outside of the standard library.
1811 Also, for now, it is not possible to write deprecation messages either.
1815 This error indicates that a `#[repr(..)]` attribute was placed on an unsupported
1818 Examples of erroneous code:
1828 struct Foo {bar: bool, baz: bool}
1836 - The `#[repr(C)]` attribute can only be placed on structs and enums
1837 - The `#[repr(packed)]` and `#[repr(simd)]` attributes only work on structs
1838 - The `#[repr(u8)]`, `#[repr(i16)]`, etc attributes only work on enums
1840 These attributes do not work on typedefs, since typedefs are just aliases.
1842 Representations like `#[repr(u8)]`, `#[repr(i64)]` are for selecting the
1843 discriminant size for C-like enums (when there is no associated data, e.g. `enum
1844 Color {Red, Blue, Green}`), effectively setting the size of the enum to the size
1845 of the provided type. Such an enum can be cast to a value of the same type as
1846 well. In short, `#[repr(u8)]` makes the enum behave like an integer with a
1847 constrained set of allowed values.
1849 Only C-like enums can be cast to numerical primitives, so this attribute will
1850 not apply to structs.
1852 `#[repr(packed)]` reduces padding to make the struct size smaller. The
1853 representation of enums isn't strictly defined in Rust, and this attribute won't
1856 `#[repr(simd)]` will give a struct consisting of a homogenous series of machine
1857 types (i.e. `u8`, `i32`, etc) a representation that permits vectorization via
1858 SIMD. This doesn't make much sense for enums since they don't consist of a
1859 single list of data.
1863 This error indicates that an `#[inline(..)]` attribute was incorrectly placed on
1864 something other than a function or method.
1866 Examples of erroneous code:
1878 `#[inline]` hints the compiler whether or not to attempt to inline a method or
1879 function. By default, the compiler does a pretty good job of figuring this out
1880 itself, but if you feel the need for annotations, `#[inline(always)]` and
1881 `#[inline(never)]` can override or force the compiler's decision.
1883 If you wish to apply this attribute to all methods in an impl, manually annotate
1884 each method; it is not possible to annotate the entire impl with an `#[inline]`
1891 register_diagnostics! {
1892 // E0006 // merged with E0005
1895 E0278, // requirement is not satisfied
1896 E0279, // requirement is not satisfied
1897 E0280, // requirement is not satisfied
1898 E0284, // cannot resolve type
1899 // E0285, // overflow evaluation builtin bounds
1900 E0298, // mismatched types between arms
1901 E0299, // mismatched types between arms
1902 // E0300, // unexpanded macro
1903 // E0304, // expected signed integer constant
1904 // E0305, // expected constant
1905 E0311, // thing may not live long enough
1906 E0312, // lifetime of reference outlives lifetime of borrowed content
1907 E0313, // lifetime of borrowed pointer outlives lifetime of captured variable
1908 E0314, // closure outlives stack frame
1909 E0315, // cannot invoke closure outside of its lifetime
1910 E0316, // nested quantification of lifetimes
1911 E0453, // overruled by outer forbid
1912 E0471, // constant evaluation error: ..
1913 E0473, // dereference of reference outside its lifetime
1914 E0474, // captured variable `..` does not outlive the enclosing closure
1915 E0475, // index of slice outside its lifetime
1916 E0476, // lifetime of the source pointer does not outlive lifetime bound...
1917 E0477, // the type `..` does not fulfill the required lifetime...
1918 E0478, // lifetime bound not satisfied
1919 E0479, // the type `..` (provided as the value of a type parameter) is...
1920 E0480, // lifetime of method receiver does not outlive the method call
1921 E0481, // lifetime of function argument does not outlive the function call
1922 E0482, // lifetime of return value does not outlive the function call
1923 E0483, // lifetime of operand does not outlive the operation
1924 E0484, // reference is not valid at the time of borrow
1925 E0485, // automatically reference is not valid at the time of borrow
1926 E0486, // type of expression contains references that are not valid during...
1927 E0487, // unsafe use of destructor: destructor might be called while...
1928 E0488, // lifetime of variable does not enclose its declaration
1929 E0489, // type/lifetime parameter not in scope here
1930 E0490, // a value of type `..` is borrowed for too long
1931 E0491, // in type `..`, reference has a longer lifetime than the data it...
1932 E0495, // cannot infer an appropriate lifetime due to conflicting requirements