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:
63 fn foo(x: Option<String>) {
72 Not-a-Number (NaN) values cannot be compared for equality and hence can never
73 match the input to a match expression. So, the following will not compile:
76 const NAN: f32 = 0.0 / 0.0;
84 To match against NaN values, you should instead use the `is_nan()` method in a
90 x if x.is_nan() => { /* ... */ }
97 This error indicates that the compiler cannot guarantee a matching pattern for
98 one or more possible inputs to a match expression. Guaranteed matches are
99 required in order to assign values to match expressions, or alternatively,
100 determine the flow of execution.
102 If you encounter this error you must alter your patterns so that every possible
103 value of the input type is matched. For types with a small number of variants
104 (like enums) you should probably cover all cases explicitly. Alternatively, the
105 underscore `_` wildcard pattern can be added after all other patterns to match
110 Patterns used to bind names must be irrefutable, that is, they must guarantee
111 that a name will be extracted in all cases. If you encounter this error you
112 probably need to use a `match` or `if let` to deal with the possibility of
117 This error indicates that the bindings in a match arm would require a value to
118 be moved into more than one location, thus violating unique ownership. Code like
119 the following is invalid as it requires the entire `Option<String>` to be moved
120 into a variable called `op_string` while simultaneously requiring the inner
121 String to be moved into a variable called `s`.
124 let x = Some("s".to_string());
126 op_string @ Some(s) => ...
135 Names bound in match arms retain their type in pattern guards. As such, if a
136 name is bound by move in a pattern, it should also be moved to wherever it is
137 referenced in the pattern guard code. Doing so however would prevent the name
138 from being available in the body of the match arm. Consider the following:
141 match Some("hi".to_string()) {
142 Some(s) if s.len() == 0 => // use s.
147 The variable `s` has type `String`, and its use in the guard is as a variable of
148 type `String`. The guard code effectively executes in a separate scope to the
149 body of the arm, so the value would be moved into this anonymous scope and
150 therefore become unavailable in the body of the arm. Although this example seems
151 innocuous, the problem is most clear when considering functions that take their
155 match Some("hi".to_string()) {
156 Some(s) if { drop(s); false } => (),
162 The value would be dropped in the guard then become unavailable not only in the
163 body of that arm but also in all subsequent arms! The solution is to bind by
164 reference when using guards or refactor the entire expression, perhaps by
165 putting the condition inside the body of the arm.
169 In a pattern, all values that don't implement the `Copy` trait have to be bound
170 the same way. The goal here is to avoid binding simultaneously by-move and
173 This limitation may be removed in a future version of Rust.
180 let x = Some((X { x: () }, X { x: () }));
182 Some((y, ref z)) => {},
187 You have two solutions:
189 Solution #1: Bind the pattern's values the same way.
194 let x = Some((X { x: () }, X { x: () }));
196 Some((ref y, ref z)) => {},
197 // or Some((y, z)) => {}
202 Solution #2: Implement the `Copy` trait for the `X` structure.
204 However, please keep in mind that the first solution should be preferred.
207 #[derive(Clone, Copy)]
210 let x = Some((X { x: () }, X { x: () }));
212 Some((y, ref z)) => {},
219 The value of statics and constants must be known at compile time, and they live
220 for the entire lifetime of a program. Creating a boxed value allocates memory on
221 the heap at runtime, and therefore cannot be done at compile time. Erroneous
225 #![feature(box_syntax)]
227 const CON : Box<i32> = box 0;
232 Initializers for constants and statics are evaluated at compile time.
233 User-defined operators rely on user-defined functions, which cannot be evaluated
243 impl Index<u8> for Foo {
246 fn index<'a>(&'a self, idx: u8) -> &'a u8 { &self.a }
249 const a: Foo = Foo { a: 0u8 };
250 const b: u8 = a[0]; // Index trait is defined by the user, bad!
253 Only operators on builtin types are allowed.
258 const a: &'static [i32] = &[1, 2, 3];
259 const b: i32 = a[0]; // Good!
264 Static and const variables can refer to other const variables. But a const
265 variable cannot refer to a static variable. For example, `Y` cannot refer to `X`
273 To fix this, the value can be extracted as a const and then used:
283 Constants can only be initialized by a constant value or, in a future
284 version of Rust, a call to a const function. This error indicates the use
285 of a path (like a::b, or x) denoting something other than one of these
286 allowed items. Example:
289 const FOO: i32 = { let x = 0; x }; // 'x' isn't a constant nor a function!
292 To avoid it, you have to replace the non-constant value:
295 const FOO: i32 = { const X : i32 = 0; X };
297 const FOO: i32 = { 0 }; // but brackets are useless here
302 The only functions that can be called in static or constant expressions are
303 `const` functions. Rust currently does not support more general compile-time
306 See [RFC 911] for more details on the design of `const fn`s.
308 [RFC 911]: https://github.com/rust-lang/rfcs/blob/master/text/0911-const-fn.md
312 Blocks in constants may only contain items (such as constant, function
313 definition, etc...) and a tail expression. Example:
316 const FOO: i32 = { let x = 0; x }; // 'x' isn't an item!
319 To avoid it, you have to replace the non-item object:
322 const FOO: i32 = { const X : i32 = 0; X };
327 References in statics and constants may only refer to immutable values. Example:
333 // these three are not allowed:
334 const CR: &'static mut i32 = &mut C;
335 static STATIC_REF: &'static mut i32 = &mut X;
336 static CONST_REF: &'static mut i32 = &mut C;
339 Statics are shared everywhere, and if they refer to mutable data one might
340 violate memory safety since holding multiple mutable references to shared data
343 If you really want global mutable state, try using `static mut` or a global
348 The value of static and const variables must be known at compile time. You
349 can't cast a pointer as an integer because we can't know what value the
352 However, pointers to other constants' addresses are allowed in constants,
357 const Y: *const u32 = &X;
360 Therefore, casting one of these non-constant pointers to an integer results
361 in a non-constant integer which lead to this error. Example:
365 const Y: usize = &X as *const u32 as usize;
371 A function call isn't allowed in the const's initialization expression
372 because the expression's value must be known at compile-time. Example of
381 fn test(&self) -> i32 {
387 const FOO: Test = Test::V1;
389 const A: i32 = FOO.test(); // You can't call Test::func() here !
393 Remember: you can't use a function call inside a const's initialization
394 expression! However, you can totally use it anywhere else:
398 const FOO: Test = Test::V1;
400 FOO.func(); // here is good
401 let x = FOO.func(); // or even here!
407 This error indicates that an attempt was made to divide by zero (or take the
408 remainder of a zero divisor) in a static or constant expression. Erroneous
412 const X: i32 = 42 / 0;
413 // error: attempted to divide by zero in a constant expression
418 Constant functions are not allowed to mutate anything. Thus, binding to an
419 argument with a mutable pattern is not allowed. For example,
422 const fn foo(mut x: u8) {
427 is bad because the function body may not mutate `x`.
429 Remove any mutable bindings from the argument list to fix this error. In case
430 you need to mutate the argument, try lazily initializing a global variable
431 instead of using a `const fn`, or refactoring the code to a functional style to
432 avoid mutation if possible.
436 When matching against a range, the compiler verifies that the range is
437 non-empty. Range patterns include both end-points, so this is equivalent to
438 requiring the start of the range to be less than or equal to the end of the
445 // This range is ok, albeit pointless.
447 // This range is empty, and the compiler can tell.
454 Trait objects like `Box<Trait>` can only be constructed when certain
455 requirements are satisfied by the trait in question.
457 Trait objects are a form of dynamic dispatch and use a dynamically sized type
458 for the inner type. So, for a given trait `Trait`, when `Trait` is treated as a
459 type, as in `Box<Trait>`, the inner type is 'unsized'. In such cases the boxed
460 pointer is a 'fat pointer' that contains an extra pointer to a table of methods
461 (among other things) for dynamic dispatch. This design mandates some
462 restrictions on the types of traits that are allowed to be used in trait
463 objects, which are collectively termed as 'object safety' rules.
465 Attempting to create a trait object for a non object-safe trait will trigger
468 There are various rules:
470 ### The trait cannot require `Self: Sized`
472 When `Trait` is treated as a type, the type does not implement the special
473 `Sized` trait, because the type does not have a known size at compile time and
474 can only be accessed behind a pointer. Thus, if we have a trait like the
478 trait Foo where Self: Sized {
483 we cannot create an object of type `Box<Foo>` or `&Foo` since in this case
484 `Self` would not be `Sized`.
486 Generally, `Self : Sized` is used to indicate that the trait should not be used
487 as a trait object. If the trait comes from your own crate, consider removing
490 ### Method references the `Self` type in its arguments or return type
492 This happens when a trait has a method like the following:
496 fn foo(&self) -> Self;
499 impl Trait for String {
500 fn foo(&self) -> Self {
506 fn foo(&self) -> Self {
512 (Note that `&self` and `&mut self` are okay, it's additional `Self` types which
515 In such a case, the compiler cannot predict the return type of `foo()` in a
516 situation like the following:
519 fn call_foo(x: Box<Trait>) {
520 let y = x.foo(); // What type is y?
525 If only some methods aren't object-safe, you can add a `where Self: Sized` bound
526 on them to mark them as explicitly unavailable to trait objects. The
527 functionality will still be available to all other implementers, including
528 `Box<Trait>` which is itself sized (assuming you `impl Trait for Box<Trait>`).
532 fn foo(&self) -> Self where Self: Sized;
537 Now, `foo()` can no longer be called on a trait object, but you will now be
538 allowed to make a trait object, and that will be able to call any object-safe
539 methods". With such a bound, one can still call `foo()` on types implementing
540 that trait that aren't behind trait objects.
542 ### Method has generic type parameters
544 As mentioned before, trait objects contain pointers to method tables. So, if we
551 impl Trait for String {
564 At compile time each implementation of `Trait` will produce a table containing
565 the various methods (and other items) related to the implementation.
567 This works fine, but when the method gains generic parameters, we can have a
570 Usually, generic parameters get _monomorphized_. For example, if I have
578 the machine code for `foo::<u8>()`, `foo::<bool>()`, `foo::<String>()`, or any
579 other type substitution is different. Hence the compiler generates the
580 implementation on-demand. If you call `foo()` with a `bool` parameter, the
581 compiler will only generate code for `foo::<bool>()`. When we have additional
582 type parameters, the number of monomorphized implementations the compiler
583 generates does not grow drastically, since the compiler will only generate an
584 implementation if the function is called with unparametrized substitutions
585 (i.e., substitutions where none of the substituted types are themselves
588 However, with trait objects we have to make a table containing _every_ object
589 that implements the trait. Now, if it has type parameters, we need to add
590 implementations for every type that implements the trait, and there could
591 theoretically be an infinite number of types.
597 fn foo<T>(&self, on: T);
600 impl Trait for String {
601 fn foo<T>(&self, on: T) {
606 fn foo<T>(&self, on: T) {
610 // 8 more implementations
613 Now, if we have the following code:
616 fn call_foo(thing: Box<Trait>) {
617 thing.foo(true); // this could be any one of the 8 types above
623 we don't just need to create a table of all implementations of all methods of
624 `Trait`, we need to create such a table, for each different type fed to
625 `foo()`. In this case this turns out to be (10 types implementing `Trait`)*(3
626 types being fed to `foo()`) = 30 implementations!
628 With real world traits these numbers can grow drastically.
630 To fix this, it is suggested to use a `where Self: Sized` bound similar to the
631 fix for the sub-error above if you do not intend to call the method with type
636 fn foo<T>(&self, on: T) where Self: Sized;
641 If this is not an option, consider replacing the type parameter with another
642 trait object (e.g. if `T: OtherTrait`, use `on: Box<OtherTrait>`). If the number
643 of types you intend to feed to this method is limited, consider manually listing
644 out the methods of different types.
646 ### Method has no receiver
648 Methods that do not take a `self` parameter can't be called since there won't be
649 a way to get a pointer to the method table for them
657 This could be called as `<Foo as Foo>::foo()`, which would not be able to pick
660 Adding a `Self: Sized` bound to these methods will generally make this compile.
664 fn foo() -> u8 where Self: Sized;
668 ### The trait cannot use `Self` as a type parameter in the supertrait listing
670 This is similar to the second sub-error, but subtler. It happens in situations
676 trait Trait: Super<Self> {
681 impl Super<Foo> for Foo{}
683 impl Trait for Foo {}
686 Here, the supertrait might have methods as follows:
690 fn get_a(&self) -> A; // note that this is object safe!
694 If the trait `Foo` was deriving from something like `Super<String>` or
695 `Super<T>` (where `Foo` itself is `Foo<T>`), this is okay, because given a type
696 `get_a()` will definitely return an object of that type.
698 However, if it derives from `Super<Self>`, even though `Super` is object safe,
699 the method `get_a()` would return an object of unknown type when called on the
700 function. `Self` type parameters let us make object safe traits no longer safe,
701 so they are forbidden when specifying supertraits.
703 There's no easy fix for this, generally code will need to be refactored so that
704 you no longer need to derive from `Super<Self>`.
708 You tried to give a type parameter to a type which doesn't need it. Erroneous
712 type X = u32<i32>; // error: type parameters are not allowed on this type
715 Please check that you used the correct type and recheck its definition. Perhaps
716 it doesn't need the type parameter.
721 type X = u32; // this compiles
724 Note that type parameters for enum-variant constructors go after the variant,
725 not after the enum (Option::None::<u32>, not Option::<u32>::None).
729 You tried to give a lifetime parameter to a type which doesn't need it.
730 Erroneous code example:
733 type X = u32<'static>; // error: lifetime parameters are not allowed on
737 Please check that the correct type was used and recheck its definition; perhaps
738 it doesn't need the lifetime parameter. Example:
746 Using unsafe functionality, is potentially dangerous and disallowed
747 by safety checks. Examples:
749 - Dereferencing raw pointers
750 - Calling functions via FFI
751 - Calling functions marked unsafe
753 These safety checks can be relaxed for a section of the code
754 by wrapping the unsafe instructions with an `unsafe` block. For instance:
757 unsafe fn f() { return; }
764 See also https://doc.rust-lang.org/book/unsafe.html
767 // This shouldn't really ever trigger since the repeated value error comes first
769 A binary can only have one entry point, and by default that entry point is the
770 function `main()`. If there are multiple such functions, please rename one.
774 This error indicates that the compiler found multiple functions with the
775 `#[main]` attribute. This is an error because there must be a unique entry
776 point into a Rust program.
780 This error indicates that the compiler found multiple functions with the
781 `#[start]` attribute. This is an error because there must be a unique entry
782 point into a Rust program.
785 // FIXME link this to the relevant turpl chapters for instilling fear of the
786 // transmute gods in the user
788 There are various restrictions on transmuting between types in Rust; for example
789 types being transmuted must have the same size. To apply all these restrictions,
790 the compiler must know the exact types that may be transmuted. When type
791 parameters are involved, this cannot always be done.
793 So, for example, the following is not allowed:
796 struct Foo<T>(Vec<T>)
798 fn foo<T>(x: Vec<T>) {
799 // we are transmuting between Vec<T> and Foo<T> here
800 let y: Foo<T> = unsafe { transmute(x) };
801 // do something with y
805 In this specific case there's a good chance that the transmute is harmless (but
806 this is not guaranteed by Rust). However, when alignment and enum optimizations
807 come into the picture, it's quite likely that the sizes may or may not match
808 with different type parameter substitutions. It's not possible to check this for
809 _all_ possible types, so `transmute()` simply only accepts types without any
810 unsubstituted type parameters.
812 If you need this, there's a good chance you're doing something wrong. Keep in
813 mind that Rust doesn't guarantee much about the layout of different structs
814 (even two structs with identical declarations may have different layouts). If
815 there is a solution that avoids the transmute entirely, try it instead.
817 If it's possible, hand-monomorphize the code by writing the function for each
818 possible type substitution. It's possible to use traits to do this cleanly,
822 trait MyTransmutableType {
823 fn transmute(Vec<Self>) -> Foo<Self>
826 impl MyTransmutableType for u8 {
827 fn transmute(x: Foo<u8>) -> Vec<u8> {
831 impl MyTransmutableType for String {
832 fn transmute(x: Foo<String>) -> Vec<String> {
836 // ... more impls for the types you intend to transmute
838 fn foo<T: MyTransmutableType>(x: Vec<T>) {
839 let y: Foo<T> = <T as MyTransmutableType>::transmute(x);
840 // do something with y
844 Each impl will be checked for a size match in the transmute as usual, and since
845 there are no unbound type parameters involved, this should compile unless there
846 is a size mismatch in one of the impls.
848 It is also possible to manually transmute:
851 ptr::read(&v as *const _ as *const SomeType) // `v` transmuted to `SomeType`
856 Lang items are already implemented in the standard library. Unless you are
857 writing a free-standing application (e.g. a kernel), you do not need to provide
860 You can build a free-standing crate by adding `#![no_std]` to the crate
868 See also https://doc.rust-lang.org/book/no-stdlib.html
872 `const` and `static` mean different things. A `const` is a compile-time
873 constant, an alias for a literal value. This property means you can match it
874 directly within a pattern.
876 The `static` keyword, on the other hand, guarantees a fixed location in memory.
877 This does not always mean that the value is constant. For example, a global
878 mutex can be declared `static` as well.
880 If you want to match against a `static`, consider using a guard instead:
883 static FORTY_TWO: i32 = 42;
885 Some(x) if x == FORTY_TWO => ...
892 In Rust, you can only move a value when its size is known at compile time.
894 To work around this restriction, consider "hiding" the value behind a reference:
895 either `&x` or `&mut x`. Since a reference has a fixed size, this lets you move
900 An if-let pattern attempts to match the pattern, and enters the body if the
901 match was successful. If the match is irrefutable (when it cannot fail to
902 match), use a regular `let`-binding instead. For instance:
905 struct Irrefutable(i32);
906 let irr = Irrefutable(0);
908 // This fails to compile because the match is irrefutable.
909 if let Irrefutable(x) = irr {
910 // This body will always be executed.
915 let Irrefutable(x) = irr;
921 A while-let pattern attempts to match the pattern, and enters the body if the
922 match was successful. If the match is irrefutable (when it cannot fail to
923 match), use a regular `let`-binding inside a `loop` instead. For instance:
926 struct Irrefutable(i32);
927 let irr = Irrefutable(0);
929 // This fails to compile because the match is irrefutable.
930 while let Irrefutable(x) = irr {
936 let Irrefutable(x) = irr;
943 Enum variants are qualified by default. For example, given this type:
952 you would match it using:
961 If you don't qualify the names, the code will bind new variables named "GET" and
962 "POST" instead. This behavior is likely not what you want, so `rustc` warns when
965 Qualified names are good practice, and most code works well with them. But if
966 you prefer them unqualified, you can import the variants into scope:
970 enum Method { GET, POST }
973 If you want others to be able to import variants from your module directly, use
978 enum Method { GET, POST }
983 When using a lifetime like `'a` in a type, it must be declared before being
986 These two examples illustrate the problem:
989 // error, use of undeclared lifetime name `'a`
990 fn foo(x: &'a str) { }
993 // error, use of undeclared lifetime name `'a`
998 These can be fixed by declaring lifetime parameters:
1001 fn foo<'a>(x: &'a str) { }
1010 Declaring certain lifetime names in parameters is disallowed. For example,
1011 because the `'static` lifetime is a special built-in lifetime name denoting
1012 the lifetime of the entire program, this is an error:
1015 // error, invalid lifetime parameter name `'static`
1016 fn foo<'static>(x: &'static str) { }
1021 A lifetime name cannot be declared more than once in the same scope. For
1025 // error, lifetime name `'a` declared twice in the same scope
1026 fn foo<'a, 'b, 'a>(x: &'a str, y: &'b str) { }
1031 This error indicates that a static or constant references itself.
1032 All statics and constants need to resolve to a value in an acyclic manner.
1034 For example, neither of the following can be sensibly compiled:
1047 This error indicates the use of a loop keyword (`break` or `continue`) inside a
1048 closure but outside of any loop. Erroneous code example:
1051 let w = || { break; }; // error: `break` inside of a closure
1054 `break` and `continue` keywords can be used as normal inside closures as long as
1055 they are also contained within a loop. To halt the execution of a closure you
1056 should instead use a return statement. Example:
1070 This error indicates the use of a loop keyword (`break` or `continue`) outside
1071 of a loop. Without a loop to break out of or continue in, no sensible action can
1072 be taken. Erroneous code example:
1076 break; // error: `break` outside of loop
1080 Please verify that you are using `break` and `continue` only in loops. Example:
1092 Functions must eventually return a value of their return type. For example, in
1093 the following function
1096 fn foo(x: u8) -> u8 {
1098 x // alternatively, `return x`
1104 if the condition is true, the value `x` is returned, but if the condition is
1105 false, control exits the `if` block and reaches a place where nothing is being
1106 returned. All possible control paths must eventually return a `u8`, which is not
1109 An easy fix for this in a complicated function is to specify a default return
1113 fn foo(x: u8) -> u8 {
1115 x // alternatively, `return x`
1117 // lots of other if branches
1118 0 // return 0 if all else fails
1122 It is advisable to find out what the unhandled cases are and check for them,
1123 returning an appropriate value or panicking if necessary.
1127 Rust lets you define functions which are known to never return, i.e. are
1128 'diverging', by marking its return type as `!`.
1130 For example, the following functions never return:
1138 foo() // foo() is diverging, so this will diverge too
1142 panic!(); // this macro internally expands to a call to a diverging function
1147 Such functions can be used in a place where a value is expected without
1148 returning a value of that type, for instance:
1154 _ => foo() // diverging function called here
1159 If the third arm of the match block is reached, since `foo()` doesn't ever
1160 return control to the match block, it is fine to use it in a place where an
1161 integer was expected. The `match` block will never finish executing, and any
1162 point where `y` (like the print statement) is needed will not be reached.
1164 However, if we had a diverging function that actually does finish execution
1172 then we would have an unknown value for `y` in the following code:
1183 In the previous example, the print statement was never reached when the wildcard
1184 match arm was hit, so we were okay with `foo()` not returning an integer that we
1185 could set to `y`. But in this example, `foo()` actually does return control, so
1186 the print statement will be executed with an uninitialized value.
1188 Obviously we cannot have functions which are allowed to be used in such
1189 positions and yet can return control. So, if you are defining a function that
1190 returns `!`, make sure that there is no way for it to actually finish executing.
1194 This is because of a type mismatch between the associated type of some
1195 trait (e.g. `T::Bar`, where `T` implements `trait Quux { type Bar; }`)
1196 and another type `U` that is required to be equal to `T::Bar`, but is not.
1199 Here is a basic example:
1202 trait Trait { type AssociatedType; }
1203 fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
1206 impl Trait for i8 { type AssociatedType = &'static str; }
1210 Here is that same example again, with some explanatory comments:
1213 trait Trait { type AssociatedType; }
1215 fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
1216 // ~~~~~~~~ ~~~~~~~~~~~~~~~~~~
1218 // This says `foo` can |
1219 // only be used with |
1221 // implements `Trait`. |
1223 // This says not only must
1224 // `T` be an impl of `Trait`
1225 // but also that the impl
1226 // must assign the type `u32`
1227 // to the associated type.
1231 impl Trait for i8 { type AssociatedType = &'static str; }
1232 ~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1237 // ... but it is an implementation
1238 // that assigns `&'static str` to
1239 // the associated type.
1242 // Here, we invoke `foo` with an `i8`, which does not satisfy
1243 // the constraint `<i8 as Trait>::AssociatedType=u32`, and
1244 // therefore the type-checker complains with this error code.
1247 Here is a more subtle instance of the same problem, that can
1248 arise with for-loops in Rust:
1251 let vs: Vec<i32> = vec![1, 2, 3, 4];
1260 The above fails because of an analogous type mismatch,
1261 though may be harder to see. Again, here are some
1262 explanatory comments for the same example:
1266 let vs = vec![1, 2, 3, 4];
1268 // `for`-loops use a protocol based on the `Iterator`
1269 // trait. Each item yielded in a `for` loop has the
1270 // type `Iterator::Item` -- that is,I `Item` is the
1271 // associated type of the concrete iterator impl.
1275 // | We borrow `vs`, iterating over a sequence of
1276 // | *references* of type `&Elem` (where `Elem` is
1277 // | vector's element type). Thus, the associated
1278 // | type `Item` must be a reference `&`-type ...
1280 // ... and `v` has the type `Iterator::Item`, as dictated by
1281 // the `for`-loop protocol ...
1287 // ... but *here*, `v` is forced to have some integral type;
1288 // only types like `u8`,`i8`,`u16`,`i16`, et cetera can
1289 // match the pattern `1` ...
1294 // ... therefore, the compiler complains, because it sees
1295 // an attempt to solve the equations
1296 // `some integral-type` = type-of-`v`
1297 // = `Iterator::Item`
1298 // = `&Elem` (i.e. `some reference type`)
1300 // which cannot possibly all be true.
1306 To avoid those issues, you have to make the types match correctly.
1307 So we can fix the previous examples like this:
1311 trait Trait { type AssociatedType; }
1312 fn foo<T>(t: T) where T: Trait<AssociatedType = &'static str> {
1315 impl Trait for i8 { type AssociatedType = &'static str; }
1318 // For-Loop Example:
1319 let vs = vec![1, 2, 3, 4];
1330 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
1331 message for when a particular trait isn't implemented on a type placed in a
1332 position that needs that trait. For example, when the following code is
1336 fn foo<T: Index<u8>>(x: T){}
1338 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1339 trait Index<Idx> { ... }
1341 foo(true); // `bool` does not implement `Index<u8>`
1344 there will be an error about `bool` not implementing `Index<u8>`, followed by a
1345 note saying "the type `bool` cannot be indexed by `u8`".
1347 As you can see, you can specify type parameters in curly braces for substitution
1348 with the actual types (using the regular format string syntax) in a given
1349 situation. Furthermore, `{Self}` will substitute to the type (in this case,
1350 `bool`) that we tried to use.
1352 This error appears when the curly braces contain an identifier which doesn't
1353 match with any of the type parameters or the string `Self`. This might happen if
1354 you misspelled a type parameter, or if you intended to use literal curly braces.
1355 If it is the latter, escape the curly braces with a second curly brace of the
1356 same type; e.g. a literal `{` is `{{`
1360 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
1361 message for when a particular trait isn't implemented on a type placed in a
1362 position that needs that trait. For example, when the following code is
1366 fn foo<T: Index<u8>>(x: T){}
1368 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1369 trait Index<Idx> { ... }
1371 foo(true); // `bool` does not implement `Index<u8>`
1374 there will be an error about `bool` not implementing `Index<u8>`, followed by a
1375 note saying "the type `bool` cannot be indexed by `u8`".
1377 As you can see, you can specify type parameters in curly braces for substitution
1378 with the actual types (using the regular format string syntax) in a given
1379 situation. Furthermore, `{Self}` will substitute to the type (in this case,
1380 `bool`) that we tried to use.
1382 This error appears when the curly braces do not contain an identifier. Please
1383 add one of the same name as a type parameter. If you intended to use literal
1384 braces, use `{{` and `}}` to escape them.
1388 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
1389 message for when a particular trait isn't implemented on a type placed in a
1390 position that needs that trait. For example, when the following code is
1394 fn foo<T: Index<u8>>(x: T){}
1396 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1397 trait Index<Idx> { ... }
1399 foo(true); // `bool` does not implement `Index<u8>`
1402 there will be an error about `bool` not implementing `Index<u8>`, followed by a
1403 note saying "the type `bool` cannot be indexed by `u8`".
1405 For this to work, some note must be specified. An empty attribute will not do
1406 anything, please remove the attribute or add some helpful note for users of the
1411 This error occurs when there was a recursive trait requirement that overflowed
1412 before it could be evaluated. Often this means that there is unbounded recursion
1413 in resolving some type bounds.
1415 For example, in the following code
1422 impl<T> Foo for T where Bar<T>: Foo {}
1425 to determine if a `T` is `Foo`, we need to check if `Bar<T>` is `Foo`. However,
1426 to do this check, we need to determine that `Bar<Bar<T>>` is `Foo`. To determine
1427 this, we check if `Bar<Bar<Bar<T>>>` is `Foo`, and so on. This is clearly a
1428 recursive requirement that can't be resolved directly.
1430 Consider changing your trait bounds so that they're less self-referential.
1434 This error occurs when a bound in an implementation of a trait does not match
1435 the bounds specified in the original trait. For example:
1443 fn foo<T>(x: T) where T: Copy {}
1447 Here, all types implementing `Foo` must have a method `foo<T>(x: T)` which can
1448 take any type `T`. However, in the `impl` for `bool`, we have added an extra
1449 bound that `T` is `Copy`, which isn't compatible with the original trait.
1451 Consider removing the bound from the method or adding the bound to the original
1452 method definition in the trait.
1456 You tried to use a type which doesn't implement some trait in a place which
1457 expected that trait. Erroneous code example:
1460 // here we declare the Foo trait with a bar method
1465 // we now declare a function which takes an object implementing the Foo trait
1466 fn some_func<T: Foo>(foo: T) {
1471 // we now call the method with the i32 type, which doesn't implement
1473 some_func(5i32); // error: the trait `Foo` is not implemented for the
1478 In order to fix this error, verify that the type you're using does implement
1486 fn some_func<T: Foo>(foo: T) {
1487 foo.bar(); // we can now use this method since i32 implements the
1491 // we implement the trait on the i32 type
1497 some_func(5i32); // ok!
1503 You tried to supply a type which doesn't implement some trait in a location
1504 which expected that trait. This error typically occurs when working with
1505 `Fn`-based types. Erroneous code example:
1508 fn foo<F: Fn()>(x: F) { }
1511 // type mismatch: the type ... implements the trait `core::ops::Fn<(_,)>`,
1512 // but the trait `core::ops::Fn<()>` is required (expected (), found tuple
1518 The issue in this case is that `foo` is defined as accepting a `Fn` with no
1519 arguments, but the closure we attempted to pass to it requires one argument.
1523 This error indicates that type inference did not result in one unique possible
1524 type, and extra information is required. In most cases this can be provided
1525 by adding a type annotation. Sometimes you need to specify a generic type
1528 A common example is the `collect` method on `Iterator`. It has a generic type
1529 parameter with a `FromIterator` bound, which for a `char` iterator is
1530 implemented by `Vec` and `String` among others. Consider the following snippet
1531 that reverses the characters of a string:
1534 let x = "hello".chars().rev().collect();
1537 In this case, the compiler cannot infer what the type of `x` should be:
1538 `Vec<char>` and `String` are both suitable candidates. To specify which type to
1539 use, you can use a type annotation on `x`:
1542 let x: Vec<char> = "hello".chars().rev().collect();
1545 It is not necessary to annotate the full type. Once the ambiguity is resolved,
1546 the compiler can infer the rest:
1549 let x: Vec<_> = "hello".chars().rev().collect();
1552 Another way to provide the compiler with enough information, is to specify the
1553 generic type parameter:
1556 let x = "hello".chars().rev().collect::<Vec<char>>();
1559 Again, you need not specify the full type if the compiler can infer it:
1562 let x = "hello".chars().rev().collect::<Vec<_>>();
1565 Apart from a method or function with a generic type parameter, this error can
1566 occur when a type parameter of a struct or trait cannot be inferred. In that
1567 case it is not always possible to use a type annotation, because all candidates
1568 have the same return type. For instance:
1572 // Some fields omitted.
1581 let number = Foo::bar();
1586 This will fail because the compiler does not know which instance of `Foo` to
1587 call `bar` on. Change `Foo::bar()` to `Foo::<T>::bar()` to resolve the error.
1591 This error indicates that the given recursion limit could not be parsed. Ensure
1592 that the value provided is a positive integer between quotes, like so:
1595 #![recursion_limit="1000"]
1600 Patterns used to bind names must be irrefutable. That is, they must guarantee
1601 that a name will be extracted in all cases. Instead of pattern matching the
1602 loop variable, consider using a `match` or `if let` inside the loop body. For
1606 // This fails because `None` is not covered.
1611 // Match inside the loop instead:
1621 if let Some(x) = item {
1629 Mutable borrows are not allowed in pattern guards, because matching cannot have
1630 side effects. Side effects could alter the matched object or the environment
1631 on which the match depends in such a way, that the match would not be
1632 exhaustive. For instance, the following would not match any arm if mutable
1633 borrows were allowed:
1638 option if option.take().is_none() => { /* impossible, option is `Some` */ },
1639 Some(_) => { } // When the previous match failed, the option became `None`.
1645 Assignments are not allowed in pattern guards, because matching cannot have
1646 side effects. Side effects could alter the matched object or the environment
1647 on which the match depends in such a way, that the match would not be
1648 exhaustive. For instance, the following would not match any arm if assignments
1654 option if { option = None; false } { },
1655 Some(_) => { } // When the previous match failed, the option became `None`.
1661 In certain cases it is possible for sub-bindings to violate memory safety.
1662 Updates to the borrow checker in a future version of Rust may remove this
1663 restriction, but for now patterns must be rewritten without sub-bindings.
1667 match Some("hi".to_string()) {
1668 ref op_string_ref @ Some(ref s) => ...
1673 match Some("hi".to_string()) {
1675 let op_string_ref = &Some(s);
1682 The `op_string_ref` binding has type `&Option<&String>` in both cases.
1684 See also https://github.com/rust-lang/rust/issues/14587
1688 In an array literal `[x; N]`, `N` is the number of elements in the array. This
1689 number cannot be negative.
1693 The length of an array is part of its type. For this reason, this length must be
1694 a compile-time constant.
1698 This error occurs when the compiler was unable to infer the concrete type of a
1699 variable. It can occur for several cases, the most common of which is a
1700 mismatch in the expected type that the compiler inferred for a variable's
1701 initializing expression, and the actual type explicitly assigned to the
1707 let x: i32 = "I am not a number!";
1708 // ~~~ ~~~~~~~~~~~~~~~~~~~~
1710 // | initializing expression;
1711 // | compiler infers type `&str`
1713 // type `i32` assigned to variable `x`
1718 Types in type definitions have lifetimes associated with them that represent
1719 how long the data stored within them is guaranteed to be live. This lifetime
1720 must be as long as the data needs to be alive, and missing the constraint that
1721 denotes this will cause this error.
1724 // This won't compile because T is not constrained, meaning the data
1725 // stored in it is not guaranteed to last as long as the reference
1730 // This will compile, because it has the constraint on the type parameter
1731 struct Foo<'a, T: 'a> {
1738 Types in type definitions have lifetimes associated with them that represent
1739 how long the data stored within them is guaranteed to be live. This lifetime
1740 must be as long as the data needs to be alive, and missing the constraint that
1741 denotes this will cause this error.
1744 // This won't compile because T is not constrained to the static lifetime
1745 // the reference needs
1750 // This will compile, because it has the constraint on the type parameter
1751 struct Foo<T: 'static> {
1758 Method calls that aren't calls to inherent `const` methods are disallowed
1759 in statics, constants, and constant functions.
1764 const BAZ: i32 = Foo(25).bar(); // error, `bar` isn't `const`
1769 const fn foo(&self) -> i32 {
1770 self.bar() // error, `bar` isn't `const`
1773 fn bar(&self) -> i32 { self.0 }
1777 For more information about `const fn`'s, see [RFC 911].
1779 [RFC 911]: https://github.com/rust-lang/rfcs/blob/master/text/0911-const-fn.md
1785 > It is invalid for a static to reference another static by value. It is
1786 > required that all references be borrowed.
1788 [RFC 246]: https://github.com/rust-lang/rfcs/pull/246
1792 The value assigned to a constant expression must be known at compile time,
1793 which is not the case when comparing raw pointers. Erroneous code example:
1796 static foo: i32 = 42;
1797 static bar: i32 = 43;
1799 static baz: bool = { (&foo as *const i32) == (&bar as *const i32) };
1800 // error: raw pointers cannot be compared in statics!
1803 Please check that the result of the comparison can be determined at compile time
1804 or isn't assigned to a constant expression. Example:
1807 static foo: i32 = 42;
1808 static bar: i32 = 43;
1810 let baz: bool = { (&foo as *const i32) == (&bar as *const i32) };
1811 // baz isn't a constant expression so it's ok
1816 The value assigned to a constant expression must be known at compile time,
1817 which is not the case when dereferencing raw pointers. Erroneous code
1821 const foo: i32 = 42;
1822 const baz: *const i32 = (&foo as *const i32);
1824 const deref: i32 = *baz;
1825 // error: raw pointers cannot be dereferenced in constants
1828 To fix this error, please do not assign this value to a constant expression.
1832 const foo: i32 = 42;
1833 const baz: *const i32 = (&foo as *const i32);
1835 unsafe { let deref: i32 = *baz; }
1836 // baz isn't a constant expression so it's ok
1839 You'll also note that this assignment must be done in an unsafe block!
1843 It is not allowed for a mutable static to allocate or have destructors. For
1847 // error: mutable statics are not allowed to have boxes
1848 static mut FOO: Option<Box<usize>> = None;
1850 // error: mutable statics are not allowed to have destructors
1851 static mut BAR: Option<Vec<i32>> = None;
1856 In Rust 1.3, the default object lifetime bounds are expected to
1857 change, as described in RFC #1156 [1]. You are getting a warning
1858 because the compiler thinks it is possible that this change will cause
1859 a compilation error in your code. It is possible, though unlikely,
1860 that this is a false alarm.
1862 The heart of the change is that where `&'a Box<SomeTrait>` used to
1863 default to `&'a Box<SomeTrait+'a>`, it now defaults to `&'a
1864 Box<SomeTrait+'static>` (here, `SomeTrait` is the name of some trait
1865 type). Note that the only types which are affected are references to
1866 boxes, like `&Box<SomeTrait>` or `&[Box<SomeTrait>]`. More common
1867 types like `&SomeTrait` or `Box<SomeTrait>` are unaffected.
1869 To silence this warning, edit your code to use an explicit bound.
1870 Most of the time, this means that you will want to change the
1871 signature of a function that you are calling. For example, if
1872 the error is reported on a call like `foo(x)`, and `foo` is
1876 fn foo(arg: &Box<SomeTrait>) { ... }
1879 you might change it to:
1882 fn foo<'a>(arg: &Box<SomeTrait+'a>) { ... }
1885 This explicitly states that you expect the trait object `SomeTrait` to
1886 contain references (with a maximum lifetime of `'a`).
1888 [1]: https://github.com/rust-lang/rfcs/pull/1156
1894 register_diagnostics! {
1895 // E0006 // merged with E0005
1898 E0229, // associated type bindings are not allowed here
1899 E0264, // unknown external lang item
1900 E0278, // requirement is not satisfied
1901 E0279, // requirement is not satisfied
1902 E0280, // requirement is not satisfied
1903 E0283, // cannot resolve type
1904 E0284, // cannot resolve type
1905 E0285, // overflow evaluation builtin bounds
1906 E0298, // mismatched types between arms
1907 E0299, // mismatched types between arms
1908 E0300, // unexpanded macro
1909 E0304, // expected signed integer constant
1910 E0305, // expected constant
1911 E0311, // thing may not live long enough
1912 E0312, // lifetime of reference outlives lifetime of borrowed content
1913 E0313, // lifetime of borrowed pointer outlives lifetime of captured variable
1914 E0314, // closure outlives stack frame
1915 E0315, // cannot invoke closure outside of its lifetime
1916 E0316, // nested quantification of lifetimes
1917 E0400 // overloaded derefs are not allowed in constants