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! {
18 This error indicates that an attempt was made to divide by zero (or take the
19 remainder of a zero divisor) in a static or constant expression. Erroneous
25 const X: i32 = 42 / 0;
26 // error: attempt to divide by zero in a constant expression
31 Trait objects like `Box<Trait>` can only be constructed when certain
32 requirements are satisfied by the trait in question.
34 Trait objects are a form of dynamic dispatch and use a dynamically sized type
35 for the inner type. So, for a given trait `Trait`, when `Trait` is treated as a
36 type, as in `Box<Trait>`, the inner type is 'unsized'. In such cases the boxed
37 pointer is a 'fat pointer' that contains an extra pointer to a table of methods
38 (among other things) for dynamic dispatch. This design mandates some
39 restrictions on the types of traits that are allowed to be used in trait
40 objects, which are collectively termed as 'object safety' rules.
42 Attempting to create a trait object for a non object-safe trait will trigger
45 There are various rules:
47 ### The trait cannot require `Self: Sized`
49 When `Trait` is treated as a type, the type does not implement the special
50 `Sized` trait, because the type does not have a known size at compile time and
51 can only be accessed behind a pointer. Thus, if we have a trait like the
55 trait Foo where Self: Sized {
60 We cannot create an object of type `Box<Foo>` or `&Foo` since in this case
61 `Self` would not be `Sized`.
63 Generally, `Self : Sized` is used to indicate that the trait should not be used
64 as a trait object. If the trait comes from your own crate, consider removing
67 ### Method references the `Self` type in its arguments or return type
69 This happens when a trait has a method like the following:
73 fn foo(&self) -> Self;
76 impl Trait for String {
77 fn foo(&self) -> Self {
83 fn foo(&self) -> Self {
89 (Note that `&self` and `&mut self` are okay, it's additional `Self` types which
92 In such a case, the compiler cannot predict the return type of `foo()` in a
93 situation like the following:
97 fn foo(&self) -> Self;
100 fn call_foo(x: Box<Trait>) {
101 let y = x.foo(); // What type is y?
106 If only some methods aren't object-safe, you can add a `where Self: Sized` bound
107 on them to mark them as explicitly unavailable to trait objects. The
108 functionality will still be available to all other implementers, including
109 `Box<Trait>` which is itself sized (assuming you `impl Trait for Box<Trait>`).
113 fn foo(&self) -> Self where Self: Sized;
118 Now, `foo()` can no longer be called on a trait object, but you will now be
119 allowed to make a trait object, and that will be able to call any object-safe
120 methods. With such a bound, one can still call `foo()` on types implementing
121 that trait that aren't behind trait objects.
123 ### Method has generic type parameters
125 As mentioned before, trait objects contain pointers to method tables. So, if we
133 impl Trait for String {
147 At compile time each implementation of `Trait` will produce a table containing
148 the various methods (and other items) related to the implementation.
150 This works fine, but when the method gains generic parameters, we can have a
153 Usually, generic parameters get _monomorphized_. For example, if I have
161 The machine code for `foo::<u8>()`, `foo::<bool>()`, `foo::<String>()`, or any
162 other type substitution is different. Hence the compiler generates the
163 implementation on-demand. If you call `foo()` with a `bool` parameter, the
164 compiler will only generate code for `foo::<bool>()`. When we have additional
165 type parameters, the number of monomorphized implementations the compiler
166 generates does not grow drastically, since the compiler will only generate an
167 implementation if the function is called with unparametrized substitutions
168 (i.e., substitutions where none of the substituted types are themselves
171 However, with trait objects we have to make a table containing _every_ object
172 that implements the trait. Now, if it has type parameters, we need to add
173 implementations for every type that implements the trait, and there could
174 theoretically be an infinite number of types.
180 fn foo<T>(&self, on: T);
184 impl Trait for String {
185 fn foo<T>(&self, on: T) {
191 fn foo<T>(&self, on: T) {
196 // 8 more implementations
199 Now, if we have the following code:
201 ```compile_fail,E0038
202 # trait Trait { fn foo<T>(&self, on: T); }
203 # impl Trait for String { fn foo<T>(&self, on: T) {} }
204 # impl Trait for u8 { fn foo<T>(&self, on: T) {} }
205 # impl Trait for bool { fn foo<T>(&self, on: T) {} }
207 fn call_foo(thing: Box<Trait>) {
208 thing.foo(true); // this could be any one of the 8 types above
214 We don't just need to create a table of all implementations of all methods of
215 `Trait`, we need to create such a table, for each different type fed to
216 `foo()`. In this case this turns out to be (10 types implementing `Trait`)*(3
217 types being fed to `foo()`) = 30 implementations!
219 With real world traits these numbers can grow drastically.
221 To fix this, it is suggested to use a `where Self: Sized` bound similar to the
222 fix for the sub-error above if you do not intend to call the method with type
227 fn foo<T>(&self, on: T) where Self: Sized;
232 If this is not an option, consider replacing the type parameter with another
233 trait object (e.g. if `T: OtherTrait`, use `on: Box<OtherTrait>`). If the number
234 of types you intend to feed to this method is limited, consider manually listing
235 out the methods of different types.
237 ### Method has no receiver
239 Methods that do not take a `self` parameter can't be called since there won't be
240 a way to get a pointer to the method table for them.
248 This could be called as `<Foo as Foo>::foo()`, which would not be able to pick
251 Adding a `Self: Sized` bound to these methods will generally make this compile.
255 fn foo() -> u8 where Self: Sized;
259 ### The trait cannot use `Self` as a type parameter in the supertrait listing
261 This is similar to the second sub-error, but subtler. It happens in situations
267 trait Trait: Super<Self> {
272 impl Super<Foo> for Foo{}
274 impl Trait for Foo {}
277 Here, the supertrait might have methods as follows:
281 fn get_a(&self) -> A; // note that this is object safe!
285 If the trait `Foo` was deriving from something like `Super<String>` or
286 `Super<T>` (where `Foo` itself is `Foo<T>`), this is okay, because given a type
287 `get_a()` will definitely return an object of that type.
289 However, if it derives from `Super<Self>`, even though `Super` is object safe,
290 the method `get_a()` would return an object of unknown type when called on the
291 function. `Self` type parameters let us make object safe traits no longer safe,
292 so they are forbidden when specifying supertraits.
294 There's no easy fix for this, generally code will need to be refactored so that
295 you no longer need to derive from `Super<Self>`.
299 When defining a recursive struct or enum, any use of the type being defined
300 from inside the definition must occur behind a pointer (like `Box` or `&`).
301 This is because structs and enums must have a well-defined size, and without
302 the pointer, the size of the type would need to be unbounded.
304 Consider the following erroneous definition of a type for a list of bytes:
306 ```compile_fail,E0072
307 // error, invalid recursive struct type
310 tail: Option<ListNode>,
314 This type cannot have a well-defined size, because it needs to be arbitrarily
315 large (since we would be able to nest `ListNode`s to any depth). Specifically,
318 size of `ListNode` = 1 byte for `head`
319 + 1 byte for the discriminant of the `Option`
323 One way to fix this is by wrapping `ListNode` in a `Box`, like so:
328 tail: Option<Box<ListNode>>,
332 This works because `Box` is a pointer, so its size is well-known.
336 This error indicates that the compiler was unable to sensibly evaluate an
337 constant expression that had to be evaluated. Attempting to divide by 0
338 or causing integer overflow are two ways to induce this error. For example:
340 ```compile_fail,E0080
347 Ensure that the expressions given can be evaluated as the desired integer type.
348 See the FFI section of the Reference for more information about using a custom
351 https://doc.rust-lang.org/reference.html#ffi-attributes
355 This error indicates that a lifetime is missing from a type. If it is an error
356 inside a function signature, the problem may be with failing to adhere to the
357 lifetime elision rules (see below).
359 Here are some simple examples of where you'll run into this error:
361 ```compile_fail,E0106
362 struct Foo { x: &bool } // error
363 struct Foo<'a> { x: &'a bool } // correct
365 struct Bar { x: Foo }
366 ^^^ expected lifetime parameter
367 struct Bar<'a> { x: Foo<'a> } // correct
369 enum Bar { A(u8), B(&bool), } // error
370 enum Bar<'a> { A(u8), B(&'a bool), } // correct
372 type MyStr = &str; // error
373 type MyStr<'a> = &'a str; // correct
376 Lifetime elision is a special, limited kind of inference for lifetimes in
377 function signatures which allows you to leave out lifetimes in certain cases.
378 For more background on lifetime elision see [the book][book-le].
380 The lifetime elision rules require that any function signature with an elided
381 output lifetime must either have
383 - exactly one input lifetime
384 - or, multiple input lifetimes, but the function must also be a method with a
385 `&self` or `&mut self` receiver
387 In the first case, the output lifetime is inferred to be the same as the unique
388 input lifetime. In the second case, the lifetime is instead inferred to be the
389 same as the lifetime on `&self` or `&mut self`.
391 Here are some examples of elision errors:
393 ```compile_fail,E0106
394 // error, no input lifetimes
397 // error, `x` and `y` have distinct lifetimes inferred
398 fn bar(x: &str, y: &str) -> &str { }
400 // error, `y`'s lifetime is inferred to be distinct from `x`'s
401 fn baz<'a>(x: &'a str, y: &str) -> &str { }
404 Here's an example that is currently an error, but may work in a future version
407 ```compile_fail,E0106
408 struct Foo<'a>(&'a str);
411 impl Quux for Foo { }
414 Lifetime elision in implementation headers was part of the lifetime elision
415 RFC. It is, however, [currently unimplemented][iss15872].
417 [book-le]: https://doc.rust-lang.org/nightly/book/first-edition/lifetimes.html#lifetime-elision
418 [iss15872]: https://github.com/rust-lang/rust/issues/15872
422 There are conflicting trait implementations for the same type.
423 Example of erroneous code:
425 ```compile_fail,E0119
427 fn get(&self) -> usize;
430 impl<T> MyTrait for T {
431 fn get(&self) -> usize { 0 }
438 impl MyTrait for Foo { // error: conflicting implementations of trait
439 // `MyTrait` for type `Foo`
440 fn get(&self) -> usize { self.value }
444 When looking for the implementation for the trait, the compiler finds
445 both the `impl<T> MyTrait for T` where T is all types and the `impl
446 MyTrait for Foo`. Since a trait cannot be implemented multiple times,
447 this is an error. So, when you write:
451 fn get(&self) -> usize;
454 impl<T> MyTrait for T {
455 fn get(&self) -> usize { 0 }
459 This makes the trait implemented on all types in the scope. So if you
460 try to implement it on another one after that, the implementations will
465 fn get(&self) -> usize;
468 impl<T> MyTrait for T {
469 fn get(&self) -> usize { 0 }
477 f.get(); // the trait is implemented so we can use it
483 Unsafe code was used outside of an unsafe function or block.
485 Erroneous code example:
487 ```compile_fail,E0133
488 unsafe fn f() { return; } // This is the unsafe code
491 f(); // error: call to unsafe function requires unsafe function or block
495 Using unsafe functionality is potentially dangerous and disallowed by safety
498 * Dereferencing raw pointers
499 * Calling functions via FFI
500 * Calling functions marked unsafe
502 These safety checks can be relaxed for a section of the code by wrapping the
503 unsafe instructions with an `unsafe` block. For instance:
506 unsafe fn f() { return; }
509 unsafe { f(); } // ok!
513 See also https://doc.rust-lang.org/book/first-edition/unsafe.html
516 // This shouldn't really ever trigger since the repeated value error comes first
518 A binary can only have one entry point, and by default that entry point is the
519 function `main()`. If there are multiple such functions, please rename one.
523 More than one function was declared with the `#[main]` attribute.
525 Erroneous code example:
527 ```compile_fail,E0137
534 fn f() {} // error: multiple functions with a #[main] attribute
537 This error indicates that the compiler found multiple functions with the
538 `#[main]` attribute. This is an error because there must be a unique entry
539 point into a Rust program. Example:
550 More than one function was declared with the `#[start]` attribute.
552 Erroneous code example:
554 ```compile_fail,E0138
558 fn foo(argc: isize, argv: *const *const u8) -> isize {}
561 fn f(argc: isize, argv: *const *const u8) -> isize {}
562 // error: multiple 'start' functions
565 This error indicates that the compiler found multiple functions with the
566 `#[start]` attribute. This is an error because there must be a unique entry
567 point into a Rust program. Example:
573 fn foo(argc: isize, argv: *const *const u8) -> isize { 0 } // ok!
578 #### Note: this error code is no longer emitted by the compiler.
580 There are various restrictions on transmuting between types in Rust; for example
581 types being transmuted must have the same size. To apply all these restrictions,
582 the compiler must know the exact types that may be transmuted. When type
583 parameters are involved, this cannot always be done.
585 So, for example, the following is not allowed:
588 use std::mem::transmute;
590 struct Foo<T>(Vec<T>);
592 fn foo<T>(x: Vec<T>) {
593 // we are transmuting between Vec<T> and Foo<F> here
594 let y: Foo<T> = unsafe { transmute(x) };
595 // do something with y
599 In this specific case there's a good chance that the transmute is harmless (but
600 this is not guaranteed by Rust). However, when alignment and enum optimizations
601 come into the picture, it's quite likely that the sizes may or may not match
602 with different type parameter substitutions. It's not possible to check this for
603 _all_ possible types, so `transmute()` simply only accepts types without any
604 unsubstituted type parameters.
606 If you need this, there's a good chance you're doing something wrong. Keep in
607 mind that Rust doesn't guarantee much about the layout of different structs
608 (even two structs with identical declarations may have different layouts). If
609 there is a solution that avoids the transmute entirely, try it instead.
611 If it's possible, hand-monomorphize the code by writing the function for each
612 possible type substitution. It's possible to use traits to do this cleanly,
616 use std::mem::transmute;
618 struct Foo<T>(Vec<T>);
620 trait MyTransmutableType: Sized {
621 fn transmute(_: Vec<Self>) -> Foo<Self>;
624 impl MyTransmutableType for u8 {
625 fn transmute(x: Vec<u8>) -> Foo<u8> {
626 unsafe { transmute(x) }
630 impl MyTransmutableType for String {
631 fn transmute(x: Vec<String>) -> Foo<String> {
632 unsafe { transmute(x) }
636 // ... more impls for the types you intend to transmute
638 fn foo<T: MyTransmutableType>(x: Vec<T>) {
639 let y: Foo<T> = <T as MyTransmutableType>::transmute(x);
640 // do something with y
644 Each impl will be checked for a size match in the transmute as usual, and since
645 there are no unbound type parameters involved, this should compile unless there
646 is a size mismatch in one of the impls.
648 It is also possible to manually transmute:
652 # let v = Some("value");
653 # type SomeType = &'static [u8];
655 ptr::read(&v as *const _ as *const SomeType) // `v` transmuted to `SomeType`
660 Note that this does not move `v` (unlike `transmute`), and may need a
661 call to `mem::forget(v)` in case you want to avoid destructors being called.
665 A lang item was redefined.
667 Erroneous code example:
669 ```compile_fail,E0152
670 #![feature(lang_items)]
672 #[lang = "panic_fmt"]
673 struct Foo; // error: duplicate lang item found: `panic_fmt`
676 Lang items are already implemented in the standard library. Unless you are
677 writing a free-standing application (e.g. a kernel), you do not need to provide
680 You can build a free-standing crate by adding `#![no_std]` to the crate
683 ```ignore (only-for-syntax-highlight)
687 See also https://doc.rust-lang.org/book/first-edition/no-stdlib.html
691 A generic type was described using parentheses rather than angle brackets. For
694 ```compile_fail,E0214
696 let v: Vec(&str) = vec!["foo"];
700 This is not currently supported: `v` should be defined as `Vec<&str>`.
701 Parentheses are currently only used with generic types when defining parameters
702 for `Fn`-family traits.
706 When using a lifetime like `'a` in a type, it must be declared before being
709 These two examples illustrate the problem:
711 ```compile_fail,E0261
712 // error, use of undeclared lifetime name `'a`
713 fn foo(x: &'a str) { }
716 // error, use of undeclared lifetime name `'a`
721 These can be fixed by declaring lifetime parameters:
724 fn foo<'a>(x: &'a str) {}
733 Declaring certain lifetime names in parameters is disallowed. For example,
734 because the `'static` lifetime is a special built-in lifetime name denoting
735 the lifetime of the entire program, this is an error:
737 ```compile_fail,E0262
738 // error, invalid lifetime parameter name `'static`
739 fn foo<'static>(x: &'static str) { }
744 A lifetime name cannot be declared more than once in the same scope. For
747 ```compile_fail,E0263
748 // error, lifetime name `'a` declared twice in the same scope
749 fn foo<'a, 'b, 'a>(x: &'a str, y: &'b str) { }
754 An unknown external lang item was used. Erroneous code example:
756 ```compile_fail,E0264
757 #![feature(lang_items)]
760 #[lang = "cake"] // error: unknown external lang item: `cake`
765 A list of available external lang items is available in
766 `src/librustc/middle/weak_lang_items.rs`. Example:
769 #![feature(lang_items)]
772 #[lang = "panic_fmt"] // ok!
779 This is because of a type mismatch between the associated type of some
780 trait (e.g. `T::Bar`, where `T` implements `trait Quux { type Bar; }`)
781 and another type `U` that is required to be equal to `T::Bar`, but is not.
784 Here is a basic example:
786 ```compile_fail,E0271
787 trait Trait { type AssociatedType; }
789 fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
793 impl Trait for i8 { type AssociatedType = &'static str; }
798 Here is that same example again, with some explanatory comments:
800 ```compile_fail,E0271
801 trait Trait { type AssociatedType; }
803 fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
804 // ~~~~~~~~ ~~~~~~~~~~~~~~~~~~
806 // This says `foo` can |
807 // only be used with |
809 // implements `Trait`. |
811 // This says not only must
812 // `T` be an impl of `Trait`
813 // but also that the impl
814 // must assign the type `u32`
815 // to the associated type.
819 impl Trait for i8 { type AssociatedType = &'static str; }
820 //~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
825 // ... but it is an implementation
826 // that assigns `&'static str` to
827 // the associated type.
830 // Here, we invoke `foo` with an `i8`, which does not satisfy
831 // the constraint `<i8 as Trait>::AssociatedType=u32`, and
832 // therefore the type-checker complains with this error code.
835 Here is a more subtle instance of the same problem, that can
836 arise with for-loops in Rust:
839 let vs: Vec<i32> = vec![1, 2, 3, 4];
848 The above fails because of an analogous type mismatch,
849 though may be harder to see. Again, here are some
850 explanatory comments for the same example:
854 let vs = vec![1, 2, 3, 4];
856 // `for`-loops use a protocol based on the `Iterator`
857 // trait. Each item yielded in a `for` loop has the
858 // type `Iterator::Item` -- that is, `Item` is the
859 // associated type of the concrete iterator impl.
863 // | We borrow `vs`, iterating over a sequence of
864 // | *references* of type `&Elem` (where `Elem` is
865 // | vector's element type). Thus, the associated
866 // | type `Item` must be a reference `&`-type ...
868 // ... and `v` has the type `Iterator::Item`, as dictated by
869 // the `for`-loop protocol ...
875 // ... but *here*, `v` is forced to have some integral type;
876 // only types like `u8`,`i8`,`u16`,`i16`, et cetera can
877 // match the pattern `1` ...
882 // ... therefore, the compiler complains, because it sees
883 // an attempt to solve the equations
884 // `some integral-type` = type-of-`v`
885 // = `Iterator::Item`
886 // = `&Elem` (i.e. `some reference type`)
888 // which cannot possibly all be true.
894 To avoid those issues, you have to make the types match correctly.
895 So we can fix the previous examples like this:
899 trait Trait { type AssociatedType; }
901 fn foo<T>(t: T) where T: Trait<AssociatedType = &'static str> {
905 impl Trait for i8 { type AssociatedType = &'static str; }
910 let vs = vec![1, 2, 3, 4];
921 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
922 message for when a particular trait isn't implemented on a type placed in a
923 position that needs that trait. For example, when the following code is
927 #![feature(on_unimplemented)]
929 fn foo<T: Index<u8>>(x: T){}
931 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
932 trait Index<Idx> { /* ... */ }
934 foo(true); // `bool` does not implement `Index<u8>`
937 There will be an error about `bool` not implementing `Index<u8>`, followed by a
938 note saying "the type `bool` cannot be indexed by `u8`".
940 As you can see, you can specify type parameters in curly braces for
941 substitution with the actual types (using the regular format string syntax) in
942 a given situation. Furthermore, `{Self}` will substitute to the type (in this
943 case, `bool`) that we tried to use.
945 This error appears when the curly braces contain an identifier which doesn't
946 match with any of the type parameters or the string `Self`. This might happen
947 if you misspelled a type parameter, or if you intended to use literal curly
948 braces. If it is the latter, escape the curly braces with a second curly brace
949 of the same type; e.g. a literal `{` is `{{`.
953 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
954 message for when a particular trait isn't implemented on a type placed in a
955 position that needs that trait. For example, when the following code is
959 #![feature(on_unimplemented)]
961 fn foo<T: Index<u8>>(x: T){}
963 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
964 trait Index<Idx> { /* ... */ }
966 foo(true); // `bool` does not implement `Index<u8>`
969 there will be an error about `bool` not implementing `Index<u8>`, followed by a
970 note saying "the type `bool` cannot be indexed by `u8`".
972 As you can see, you can specify type parameters in curly braces for
973 substitution with the actual types (using the regular format string syntax) in
974 a given situation. Furthermore, `{Self}` will substitute to the type (in this
975 case, `bool`) that we tried to use.
977 This error appears when the curly braces do not contain an identifier. Please
978 add one of the same name as a type parameter. If you intended to use literal
979 braces, use `{{` and `}}` to escape them.
983 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
984 message for when a particular trait isn't implemented on a type placed in a
985 position that needs that trait. For example, when the following code is
989 #![feature(on_unimplemented)]
991 fn foo<T: Index<u8>>(x: T){}
993 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
994 trait Index<Idx> { /* ... */ }
996 foo(true); // `bool` does not implement `Index<u8>`
999 there will be an error about `bool` not implementing `Index<u8>`, followed by a
1000 note saying "the type `bool` cannot be indexed by `u8`".
1002 For this to work, some note must be specified. An empty attribute will not do
1003 anything, please remove the attribute or add some helpful note for users of the
1008 This error occurs when there was a recursive trait requirement that overflowed
1009 before it could be evaluated. Often this means that there is unbounded
1010 recursion in resolving some type bounds.
1012 For example, in the following code:
1014 ```compile_fail,E0275
1019 impl<T> Foo for T where Bar<T>: Foo {}
1022 To determine if a `T` is `Foo`, we need to check if `Bar<T>` is `Foo`. However,
1023 to do this check, we need to determine that `Bar<Bar<T>>` is `Foo`. To
1024 determine this, we check if `Bar<Bar<Bar<T>>>` is `Foo`, and so on. This is
1025 clearly a recursive requirement that can't be resolved directly.
1027 Consider changing your trait bounds so that they're less self-referential.
1031 This error occurs when a bound in an implementation of a trait does not match
1032 the bounds specified in the original trait. For example:
1034 ```compile_fail,E0276
1040 fn foo<T>(x: T) where T: Copy {}
1044 Here, all types implementing `Foo` must have a method `foo<T>(x: T)` which can
1045 take any type `T`. However, in the `impl` for `bool`, we have added an extra
1046 bound that `T` is `Copy`, which isn't compatible with the original trait.
1048 Consider removing the bound from the method or adding the bound to the original
1049 method definition in the trait.
1053 You tried to use a type which doesn't implement some trait in a place which
1054 expected that trait. Erroneous code example:
1056 ```compile_fail,E0277
1057 // here we declare the Foo trait with a bar method
1062 // we now declare a function which takes an object implementing the Foo trait
1063 fn some_func<T: Foo>(foo: T) {
1068 // we now call the method with the i32 type, which doesn't implement
1070 some_func(5i32); // error: the trait bound `i32 : Foo` is not satisfied
1074 In order to fix this error, verify that the type you're using does implement
1082 fn some_func<T: Foo>(foo: T) {
1083 foo.bar(); // we can now use this method since i32 implements the
1087 // we implement the trait on the i32 type
1093 some_func(5i32); // ok!
1097 Or in a generic context, an erroneous code example would look like:
1099 ```compile_fail,E0277
1100 fn some_func<T>(foo: T) {
1101 println!("{:?}", foo); // error: the trait `core::fmt::Debug` is not
1102 // implemented for the type `T`
1106 // We now call the method with the i32 type,
1107 // which *does* implement the Debug trait.
1112 Note that the error here is in the definition of the generic function: Although
1113 we only call it with a parameter that does implement `Debug`, the compiler
1114 still rejects the function: It must work with all possible input types. In
1115 order to make this example compile, we need to restrict the generic type we're
1121 // Restrict the input type to types that implement Debug.
1122 fn some_func<T: fmt::Debug>(foo: T) {
1123 println!("{:?}", foo);
1127 // Calling the method is still fine, as i32 implements Debug.
1130 // This would fail to compile now:
1131 // struct WithoutDebug;
1132 // some_func(WithoutDebug);
1136 Rust only looks at the signature of the called function, as such it must
1137 already specify all requirements that will be used for every type parameter.
1141 You tried to supply a type which doesn't implement some trait in a location
1142 which expected that trait. This error typically occurs when working with
1143 `Fn`-based types. Erroneous code example:
1145 ```compile_fail,E0281
1146 fn foo<F: Fn(usize)>(x: F) { }
1149 // type mismatch: ... implements the trait `core::ops::Fn<(String,)>`,
1150 // but the trait `core::ops::Fn<(usize,)>` is required
1152 foo(|y: String| { });
1156 The issue in this case is that `foo` is defined as accepting a `Fn` with one
1157 argument of type `String`, but the closure we attempted to pass to it requires
1158 one arguments of type `usize`.
1162 This error indicates that type inference did not result in one unique possible
1163 type, and extra information is required. In most cases this can be provided
1164 by adding a type annotation. Sometimes you need to specify a generic type
1167 A common example is the `collect` method on `Iterator`. It has a generic type
1168 parameter with a `FromIterator` bound, which for a `char` iterator is
1169 implemented by `Vec` and `String` among others. Consider the following snippet
1170 that reverses the characters of a string:
1172 ```compile_fail,E0282
1173 let x = "hello".chars().rev().collect();
1176 In this case, the compiler cannot infer what the type of `x` should be:
1177 `Vec<char>` and `String` are both suitable candidates. To specify which type to
1178 use, you can use a type annotation on `x`:
1181 let x: Vec<char> = "hello".chars().rev().collect();
1184 It is not necessary to annotate the full type. Once the ambiguity is resolved,
1185 the compiler can infer the rest:
1188 let x: Vec<_> = "hello".chars().rev().collect();
1191 Another way to provide the compiler with enough information, is to specify the
1192 generic type parameter:
1195 let x = "hello".chars().rev().collect::<Vec<char>>();
1198 Again, you need not specify the full type if the compiler can infer it:
1201 let x = "hello".chars().rev().collect::<Vec<_>>();
1204 Apart from a method or function with a generic type parameter, this error can
1205 occur when a type parameter of a struct or trait cannot be inferred. In that
1206 case it is not always possible to use a type annotation, because all candidates
1207 have the same return type. For instance:
1209 ```compile_fail,E0282
1220 let number = Foo::bar();
1225 This will fail because the compiler does not know which instance of `Foo` to
1226 call `bar` on. Change `Foo::bar()` to `Foo::<T>::bar()` to resolve the error.
1230 This error occurs when the compiler doesn't have enough information
1231 to unambiguously choose an implementation.
1235 ```compile_fail,E0283
1242 impl Generator for Impl {
1243 fn create() -> u32 { 1 }
1248 impl Generator for AnotherImpl {
1249 fn create() -> u32 { 2 }
1253 let cont: u32 = Generator::create();
1254 // error, impossible to choose one of Generator trait implementation
1255 // Impl or AnotherImpl? Maybe anything else?
1259 To resolve this error use the concrete type:
1268 impl Generator for AnotherImpl {
1269 fn create() -> u32 { 2 }
1273 let gen1 = AnotherImpl::create();
1275 // if there are multiple methods with same name (different traits)
1276 let gen2 = <AnotherImpl as Generator>::create();
1282 This error indicates that the given recursion limit could not be parsed. Ensure
1283 that the value provided is a positive integer between quotes.
1285 Erroneous code example:
1287 ```compile_fail,E0296
1293 And a working example:
1296 #![recursion_limit="1000"]
1303 This error occurs when the compiler was unable to infer the concrete type of a
1304 variable. It can occur for several cases, the most common of which is a
1305 mismatch in the expected type that the compiler inferred for a variable's
1306 initializing expression, and the actual type explicitly assigned to the
1311 ```compile_fail,E0308
1312 let x: i32 = "I am not a number!";
1313 // ~~~ ~~~~~~~~~~~~~~~~~~~~
1315 // | initializing expression;
1316 // | compiler infers type `&str`
1318 // type `i32` assigned to variable `x`
1323 Types in type definitions have lifetimes associated with them that represent
1324 how long the data stored within them is guaranteed to be live. This lifetime
1325 must be as long as the data needs to be alive, and missing the constraint that
1326 denotes this will cause this error.
1328 ```compile_fail,E0309
1329 // This won't compile because T is not constrained, meaning the data
1330 // stored in it is not guaranteed to last as long as the reference
1336 This will compile, because it has the constraint on the type parameter:
1339 struct Foo<'a, T: 'a> {
1344 To see why this is important, consider the case where `T` is itself a reference
1345 (e.g., `T = &str`). If we don't include the restriction that `T: 'a`, the
1346 following code would be perfectly legal:
1348 ```compile_fail,E0309
1354 let v = "42".to_string();
1355 let f = Foo{foo: &v};
1357 println!("{}", f.foo); // but we've already dropped v!
1363 Types in type definitions have lifetimes associated with them that represent
1364 how long the data stored within them is guaranteed to be live. This lifetime
1365 must be as long as the data needs to be alive, and missing the constraint that
1366 denotes this will cause this error.
1368 ```compile_fail,E0310
1369 // This won't compile because T is not constrained to the static lifetime
1370 // the reference needs
1376 This will compile, because it has the constraint on the type parameter:
1379 struct Foo<T: 'static> {
1386 A lifetime of reference outlives lifetime of borrowed content.
1388 Erroneous code example:
1390 ```compile_fail,E0312
1391 fn make_child<'human, 'elve>(x: &mut &'human isize, y: &mut &'elve isize) {
1393 // error: lifetime of reference outlives lifetime of borrowed content
1397 The compiler cannot determine if the `human` lifetime will live long enough
1398 to keep up on the elve one. To solve this error, you have to give an
1399 explicit lifetime hierarchy:
1402 fn make_child<'human, 'elve: 'human>(x: &mut &'human isize,
1403 y: &mut &'elve isize) {
1408 Or use the same lifetime for every variable:
1411 fn make_child<'elve>(x: &mut &'elve isize, y: &mut &'elve isize) {
1418 This error occurs when an `if` expression without an `else` block is used in a
1419 context where a type other than `()` is expected, for example a `let`
1422 ```compile_fail,E0317
1425 let a = if x == 5 { 1 };
1429 An `if` expression without an `else` block has the type `()`, so this is a type
1430 error. To resolve it, add an `else` block having the same type as the `if`
1435 This error indicates that some types or traits depend on each other
1436 and therefore cannot be constructed.
1438 The following example contains a circular dependency between two traits:
1440 ```compile_fail,E0391
1441 trait FirstTrait : SecondTrait {
1445 trait SecondTrait : FirstTrait {
1452 #### Note: this error code is no longer emitted by the compiler.
1454 In Rust 1.3, the default object lifetime bounds are expected to change, as
1455 described in [RFC 1156]. You are getting a warning because the compiler
1456 thinks it is possible that this change will cause a compilation error in your
1457 code. It is possible, though unlikely, that this is a false alarm.
1459 The heart of the change is that where `&'a Box<SomeTrait>` used to default to
1460 `&'a Box<SomeTrait+'a>`, it now defaults to `&'a Box<SomeTrait+'static>` (here,
1461 `SomeTrait` is the name of some trait type). Note that the only types which are
1462 affected are references to boxes, like `&Box<SomeTrait>` or
1463 `&[Box<SomeTrait>]`. More common types like `&SomeTrait` or `Box<SomeTrait>`
1466 To silence this warning, edit your code to use an explicit bound. Most of the
1467 time, this means that you will want to change the signature of a function that
1468 you are calling. For example, if the error is reported on a call like `foo(x)`,
1469 and `foo` is defined as follows:
1472 # trait SomeTrait {}
1473 fn foo(arg: &Box<SomeTrait>) { /* ... */ }
1476 You might change it to:
1479 # trait SomeTrait {}
1480 fn foo<'a>(arg: &'a Box<SomeTrait+'a>) { /* ... */ }
1483 This explicitly states that you expect the trait object `SomeTrait` to contain
1484 references (with a maximum lifetime of `'a`).
1486 [RFC 1156]: https://github.com/rust-lang/rfcs/blob/master/text/1156-adjust-default-object-bounds.md
1490 An invalid lint attribute has been given. Erroneous code example:
1492 ```compile_fail,E0452
1493 #![allow(foo = "")] // error: malformed lint attribute
1496 Lint attributes only accept a list of identifiers (where each identifier is a
1497 lint name). Ensure the attribute is of this form:
1500 #![allow(foo)] // ok!
1502 #![allow(foo, foo2)] // ok!
1507 A lint check attribute was overruled by a `forbid` directive set as an
1508 attribute on an enclosing scope, or on the command line with the `-F` option.
1510 Example of erroneous code:
1512 ```compile_fail,E0453
1513 #![forbid(non_snake_case)]
1515 #[allow(non_snake_case)]
1517 let MyNumber = 2; // error: allow(non_snake_case) overruled by outer
1518 // forbid(non_snake_case)
1522 The `forbid` lint setting, like `deny`, turns the corresponding compiler
1523 warning into a hard error. Unlike `deny`, `forbid` prevents itself from being
1524 overridden by inner attributes.
1526 If you're sure you want to override the lint check, you can change `forbid` to
1527 `deny` (or use `-D` instead of `-F` if the `forbid` setting was given as a
1528 command-line option) to allow the inner lint check attribute:
1531 #![deny(non_snake_case)]
1533 #[allow(non_snake_case)]
1535 let MyNumber = 2; // ok!
1539 Otherwise, edit the code to pass the lint check, and remove the overruled
1543 #![forbid(non_snake_case)]
1552 A lifetime bound was not satisfied.
1554 Erroneous code example:
1556 ```compile_fail,E0478
1557 // Check that the explicit lifetime bound (`'SnowWhite`, in this example) must
1558 // outlive all the superbounds from the trait (`'kiss`, in this example).
1560 trait Wedding<'t>: 't { }
1562 struct Prince<'kiss, 'SnowWhite> {
1563 child: Box<Wedding<'kiss> + 'SnowWhite>,
1564 // error: lifetime bound not satisfied
1568 In this example, the `'SnowWhite` lifetime is supposed to outlive the `'kiss`
1569 lifetime but the declaration of the `Prince` struct doesn't enforce it. To fix
1570 this issue, you need to specify it:
1573 trait Wedding<'t>: 't { }
1575 struct Prince<'kiss, 'SnowWhite: 'kiss> { // You say here that 'kiss must live
1576 // longer than 'SnowWhite.
1577 child: Box<Wedding<'kiss> + 'SnowWhite>, // And now it's all good!
1583 A reference has a longer lifetime than the data it references.
1585 Erroneous code example:
1587 ```compile_fail,E0491
1588 // struct containing a reference requires a lifetime parameter,
1589 // because the data the reference points to must outlive the struct (see E0106)
1594 // However, a nested struct like this, the signature itself does not tell
1595 // whether 'a outlives 'b or the other way around.
1596 // So it could be possible that 'b of reference outlives 'a of the data.
1597 struct Nested<'a, 'b> {
1598 ref_struct: &'b Struct<'a>, // compile error E0491
1602 To fix this issue, you can specify a bound to the lifetime like below:
1609 // 'a: 'b means 'a outlives 'b
1610 struct Nested<'a: 'b, 'b> {
1611 ref_struct: &'b Struct<'a>,
1617 A lifetime name is shadowing another lifetime name. Erroneous code example:
1619 ```compile_fail,E0496
1625 fn f<'a>(x: &'a i32) { // error: lifetime name `'a` shadows a lifetime
1626 // name that is already in scope
1631 Please change the name of one of the lifetimes to remove this error. Example:
1639 fn f<'b>(x: &'b i32) { // ok!
1649 A stability attribute was used outside of the standard library. Erroneous code
1653 #[stable] // error: stability attributes may not be used outside of the
1658 It is not possible to use stability attributes outside of the standard library.
1659 Also, for now, it is not possible to write deprecation messages either.
1663 Transmute with two differently sized types was attempted. Erroneous code
1666 ```compile_fail,E0512
1667 fn takes_u8(_: u8) {}
1670 unsafe { takes_u8(::std::mem::transmute(0u16)); }
1671 // error: transmute called with types of different sizes
1675 Please use types with same size or use the expected type directly. Example:
1678 fn takes_u8(_: u8) {}
1681 unsafe { takes_u8(::std::mem::transmute(0i8)); } // ok!
1683 unsafe { takes_u8(0u8); } // ok!
1689 This error indicates that a `#[repr(..)]` attribute was placed on an
1692 Examples of erroneous code:
1694 ```compile_fail,E0517
1702 struct Foo {bar: bool, baz: bool}
1710 * The `#[repr(C)]` attribute can only be placed on structs and enums.
1711 * The `#[repr(packed)]` and `#[repr(simd)]` attributes only work on structs.
1712 * The `#[repr(u8)]`, `#[repr(i16)]`, etc attributes only work on enums.
1714 These attributes do not work on typedefs, since typedefs are just aliases.
1716 Representations like `#[repr(u8)]`, `#[repr(i64)]` are for selecting the
1717 discriminant size for C-like enums (when there is no associated data, e.g.
1718 `enum Color {Red, Blue, Green}`), effectively setting the size of the enum to
1719 the size of the provided type. Such an enum can be cast to a value of the same
1720 type as well. In short, `#[repr(u8)]` makes the enum behave like an integer
1721 with a constrained set of allowed values.
1723 Only C-like enums can be cast to numerical primitives, so this attribute will
1724 not apply to structs.
1726 `#[repr(packed)]` reduces padding to make the struct size smaller. The
1727 representation of enums isn't strictly defined in Rust, and this attribute
1728 won't work on enums.
1730 `#[repr(simd)]` will give a struct consisting of a homogeneous series of machine
1731 types (i.e. `u8`, `i32`, etc) a representation that permits vectorization via
1732 SIMD. This doesn't make much sense for enums since they don't consist of a
1733 single list of data.
1737 This error indicates that an `#[inline(..)]` attribute was incorrectly placed
1738 on something other than a function or method.
1740 Examples of erroneous code:
1742 ```compile_fail,E0518
1752 `#[inline]` hints the compiler whether or not to attempt to inline a method or
1753 function. By default, the compiler does a pretty good job of figuring this out
1754 itself, but if you feel the need for annotations, `#[inline(always)]` and
1755 `#[inline(never)]` can override or force the compiler's decision.
1757 If you wish to apply this attribute to all methods in an impl, manually annotate
1758 each method; it is not possible to annotate the entire impl with an `#[inline]`
1763 The lang attribute is intended for marking special items that are built-in to
1764 Rust itself. This includes special traits (like `Copy` and `Sized`) that affect
1765 how the compiler behaves, as well as special functions that may be automatically
1766 invoked (such as the handler for out-of-bounds accesses when indexing a slice).
1767 Erroneous code example:
1769 ```compile_fail,E0522
1770 #![feature(lang_items)]
1773 fn cookie() -> ! { // error: definition of an unknown language item: `cookie`
1780 A closure was used but didn't implement the expected trait.
1782 Erroneous code example:
1784 ```compile_fail,E0525
1788 fn bar<T: Fn(u32)>(_: T) {}
1792 let closure = |_| foo(x); // error: expected a closure that implements
1793 // the `Fn` trait, but this closure only
1794 // implements `FnOnce`
1799 In the example above, `closure` is an `FnOnce` closure whereas the `bar`
1800 function expected an `Fn` closure. In this case, it's simple to fix the issue,
1801 you just have to implement `Copy` and `Clone` traits on `struct X` and it'll
1805 #[derive(Clone, Copy)] // We implement `Clone` and `Copy` traits.
1809 fn bar<T: Fn(u32)>(_: T) {}
1813 let closure = |_| foo(x);
1814 bar(closure); // ok!
1818 To understand better how closures work in Rust, read:
1819 https://doc.rust-lang.org/book/first-edition/closures.html
1823 The `main` function was incorrectly declared.
1825 Erroneous code example:
1827 ```compile_fail,E0580
1828 fn main() -> i32 { // error: main function has wrong type
1833 The `main` function prototype should never take arguments or return type.
1842 If you want to get command-line arguments, use `std::env::args`. To exit with a
1843 specified exit code, use `std::process::exit`.
1847 Per [RFC 401][rfc401], if you have a function declaration `foo`:
1850 // For the purposes of this explanation, all of these
1851 // different kinds of `fn` declarations are equivalent:
1853 fn foo(x: S) { /* ... */ }
1854 # #[cfg(for_demonstration_only)]
1855 extern "C" { fn foo(x: S); }
1856 # #[cfg(for_demonstration_only)]
1857 impl S { fn foo(self) { /* ... */ } }
1860 the type of `foo` is **not** `fn(S)`, as one might expect.
1861 Rather, it is a unique, zero-sized marker type written here as `typeof(foo)`.
1862 However, `typeof(foo)` can be _coerced_ to a function pointer `fn(S)`,
1863 so you rarely notice this:
1868 let x: fn(S) = foo; // OK, coerces
1871 The reason that this matter is that the type `fn(S)` is not specific to
1872 any particular function: it's a function _pointer_. So calling `x()` results
1873 in a virtual call, whereas `foo()` is statically dispatched, because the type
1874 of `foo` tells us precisely what function is being called.
1876 As noted above, coercions mean that most code doesn't have to be
1877 concerned with this distinction. However, you can tell the difference
1878 when using **transmute** to convert a fn item into a fn pointer.
1880 This is sometimes done as part of an FFI:
1882 ```compile_fail,E0591
1883 extern "C" fn foo(userdata: Box<i32>) {
1887 # fn callback(_: extern "C" fn(*mut i32)) {}
1888 # use std::mem::transmute;
1890 let f: extern "C" fn(*mut i32) = transmute(foo);
1895 Here, transmute is being used to convert the types of the fn arguments.
1896 This pattern is incorrect because, because the type of `foo` is a function
1897 **item** (`typeof(foo)`), which is zero-sized, and the target type (`fn()`)
1898 is a function pointer, which is not zero-sized.
1899 This pattern should be rewritten. There are a few possible ways to do this:
1901 - change the original fn declaration to match the expected signature,
1902 and do the cast in the fn body (the prefered option)
1903 - cast the fn item fo a fn pointer before calling transmute, as shown here:
1906 # extern "C" fn foo(_: Box<i32>) {}
1907 # use std::mem::transmute;
1909 let f: extern "C" fn(*mut i32) = transmute(foo as extern "C" fn(_));
1910 let f: extern "C" fn(*mut i32) = transmute(foo as usize); // works too
1914 The same applies to transmutes to `*mut fn()`, which were observedin practice.
1915 Note though that use of this type is generally incorrect.
1916 The intention is typically to describe a function pointer, but just `fn()`
1917 alone suffices for that. `*mut fn()` is a pointer to a fn pointer.
1918 (Since these values are typically just passed to C code, however, this rarely
1919 makes a difference in practice.)
1921 [rfc401]: https://github.com/rust-lang/rfcs/blob/master/text/0401-coercions.md
1925 You tried to supply an `Fn`-based type with an incorrect number of arguments
1926 than what was expected.
1928 Erroneous code example:
1930 ```compile_fail,E0593
1931 fn foo<F: Fn()>(x: F) { }
1934 // [E0593] closure takes 1 argument but 0 arguments are required
1941 No `main` function was found in a binary crate. To fix this error, just add a
1942 `main` function. For example:
1946 // Your program will start here.
1947 println!("Hello world!");
1951 If you don't know the basics of Rust, you can go look to the Rust Book to get
1952 started: https://doc.rust-lang.org/book/
1956 An unknown lint was used on the command line.
1961 rustc -D bogus omse_file.rs
1964 Maybe you just misspelled the lint name or the lint doesn't exist anymore.
1965 Either way, try to update/remove it in order to fix the error.
1969 This error code indicates a mismatch between the lifetimes appearing in the
1970 function signature (i.e., the parameter types and the return type) and the
1971 data-flow found in the function body.
1973 Erroneous code example:
1975 ```compile_fail,E0621
1976 fn foo<'a>(x: &'a i32, y: &i32) -> &'a i32 { // error: explicit lifetime
1977 // required in the type of
1979 if x > y { x } else { y }
1983 In the code above, the function is returning data borrowed from either `x` or
1984 `y`, but the `'a` annotation indicates that it is returning data only from `x`.
1985 To fix the error, the signature and the body must be made to match. Typically,
1986 this is done by updating the function signature. So, in this case, we change
1987 the type of `y` to `&'a i32`, like so:
1990 fn foo<'a>(x: &'a i32, y: &'a i32) -> &'a i32 {
1991 if x > y { x } else { y }
1995 Now the signature indicates that the function data borrowed from either `x` or
1996 `y`. Alternatively, you could change the body to not return data from `y`:
1999 fn foo<'a>(x: &'a i32, y: &i32) -> &'a i32 {
2008 register_diagnostics! {
2009 // E0006 // merged with E0005
2010 // E0101, // replaced with E0282
2011 // E0102, // replaced with E0282
2014 E0278, // requirement is not satisfied
2015 E0279, // requirement is not satisfied
2016 E0280, // requirement is not satisfied
2017 E0284, // cannot resolve type
2018 // E0285, // overflow evaluation builtin bounds
2019 // E0300, // unexpanded macro
2020 // E0304, // expected signed integer constant
2021 // E0305, // expected constant
2022 E0311, // thing may not live long enough
2023 E0313, // lifetime of borrowed pointer outlives lifetime of captured variable
2024 E0314, // closure outlives stack frame
2025 E0315, // cannot invoke closure outside of its lifetime
2026 E0316, // nested quantification of lifetimes
2027 E0320, // recursive overflow during dropck
2028 E0473, // dereference of reference outside its lifetime
2029 E0474, // captured variable `..` does not outlive the enclosing closure
2030 E0475, // index of slice outside its lifetime
2031 E0476, // lifetime of the source pointer does not outlive lifetime bound...
2032 E0477, // the type `..` does not fulfill the required lifetime...
2033 E0479, // the type `..` (provided as the value of a type parameter) is...
2034 E0480, // lifetime of method receiver does not outlive the method call
2035 E0481, // lifetime of function argument does not outlive the function call
2036 E0482, // lifetime of return value does not outlive the function call
2037 E0483, // lifetime of operand does not outlive the operation
2038 E0484, // reference is not valid at the time of borrow
2039 E0485, // automatically reference is not valid at the time of borrow
2040 E0486, // type of expression contains references that are not valid during...
2041 E0487, // unsafe use of destructor: destructor might be called while...
2042 E0488, // lifetime of variable does not enclose its declaration
2043 E0489, // type/lifetime parameter not in scope here
2044 E0490, // a value of type `..` is borrowed for too long
2045 E0495, // cannot infer an appropriate lifetime due to conflicting requirements
2046 E0566, // conflicting representation hints
2047 E0623, // lifetime mismatch where both parameters are anonymous regions