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:
202 fn call_foo(thing: Box<Trait>) {
203 thing.foo(true); // this could be any one of the 8 types above
209 We don't just need to create a table of all implementations of all methods of
210 `Trait`, we need to create such a table, for each different type fed to
211 `foo()`. In this case this turns out to be (10 types implementing `Trait`)*(3
212 types being fed to `foo()`) = 30 implementations!
214 With real world traits these numbers can grow drastically.
216 To fix this, it is suggested to use a `where Self: Sized` bound similar to the
217 fix for the sub-error above if you do not intend to call the method with type
222 fn foo<T>(&self, on: T) where Self: Sized;
227 If this is not an option, consider replacing the type parameter with another
228 trait object (e.g. if `T: OtherTrait`, use `on: Box<OtherTrait>`). If the number
229 of types you intend to feed to this method is limited, consider manually listing
230 out the methods of different types.
232 ### Method has no receiver
234 Methods that do not take a `self` parameter can't be called since there won't be
235 a way to get a pointer to the method table for them.
243 This could be called as `<Foo as Foo>::foo()`, which would not be able to pick
246 Adding a `Self: Sized` bound to these methods will generally make this compile.
250 fn foo() -> u8 where Self: Sized;
254 ### The trait cannot use `Self` as a type parameter in the supertrait listing
256 This is similar to the second sub-error, but subtler. It happens in situations
262 trait Trait: Super<Self> {
267 impl Super<Foo> for Foo{}
269 impl Trait for Foo {}
272 Here, the supertrait might have methods as follows:
276 fn get_a(&self) -> A; // note that this is object safe!
280 If the trait `Foo` was deriving from something like `Super<String>` or
281 `Super<T>` (where `Foo` itself is `Foo<T>`), this is okay, because given a type
282 `get_a()` will definitely return an object of that type.
284 However, if it derives from `Super<Self>`, even though `Super` is object safe,
285 the method `get_a()` would return an object of unknown type when called on the
286 function. `Self` type parameters let us make object safe traits no longer safe,
287 so they are forbidden when specifying supertraits.
289 There's no easy fix for this, generally code will need to be refactored so that
290 you no longer need to derive from `Super<Self>`.
294 When defining a recursive struct or enum, any use of the type being defined
295 from inside the definition must occur behind a pointer (like `Box` or `&`).
296 This is because structs and enums must have a well-defined size, and without
297 the pointer, the size of the type would need to be unbounded.
299 Consider the following erroneous definition of a type for a list of bytes:
301 ```compile_fail,E0072
302 // error, invalid recursive struct type
305 tail: Option<ListNode>,
309 This type cannot have a well-defined size, because it needs to be arbitrarily
310 large (since we would be able to nest `ListNode`s to any depth). Specifically,
313 size of `ListNode` = 1 byte for `head`
314 + 1 byte for the discriminant of the `Option`
318 One way to fix this is by wrapping `ListNode` in a `Box`, like so:
323 tail: Option<Box<ListNode>>,
327 This works because `Box` is a pointer, so its size is well-known.
331 You tried to give a type parameter to a type which doesn't need it. Erroneous
334 ```compile_fail,E0109
335 type X = u32<i32>; // error: type parameters are not allowed on this type
338 Please check that you used the correct type and recheck its definition. Perhaps
339 it doesn't need the type parameter.
344 type X = u32; // this compiles
347 Note that type parameters for enum-variant constructors go after the variant,
348 not after the enum (Option::None::<u32>, not Option::<u32>::None).
352 You tried to give a lifetime parameter to a type which doesn't need it.
353 Erroneous code example:
355 ```compile_fail,E0110
356 type X = u32<'static>; // error: lifetime parameters are not allowed on
360 Please check that the correct type was used and recheck its definition; perhaps
361 it doesn't need the lifetime parameter. Example:
369 Unsafe code was used outside of an unsafe function or block.
371 Erroneous code example:
373 ```compile_fail,E0133
374 unsafe fn f() { return; } // This is the unsafe code
377 f(); // error: call to unsafe function requires unsafe function or block
381 Using unsafe functionality is potentially dangerous and disallowed by safety
384 * Dereferencing raw pointers
385 * Calling functions via FFI
386 * Calling functions marked unsafe
388 These safety checks can be relaxed for a section of the code by wrapping the
389 unsafe instructions with an `unsafe` block. For instance:
392 unsafe fn f() { return; }
395 unsafe { f(); } // ok!
399 See also https://doc.rust-lang.org/book/unsafe.html
402 // This shouldn't really ever trigger since the repeated value error comes first
404 A binary can only have one entry point, and by default that entry point is the
405 function `main()`. If there are multiple such functions, please rename one.
409 More than one function was declared with the `#[main]` attribute.
411 Erroneous code example:
413 ```compile_fail,E0137
420 fn f() {} // error: multiple functions with a #[main] attribute
423 This error indicates that the compiler found multiple functions with the
424 `#[main]` attribute. This is an error because there must be a unique entry
425 point into a Rust program. Example:
436 More than one function was declared with the `#[start]` attribute.
438 Erroneous code example:
440 ```compile_fail,E0138
444 fn foo(argc: isize, argv: *const *const u8) -> isize {}
447 fn f(argc: isize, argv: *const *const u8) -> isize {}
448 // error: multiple 'start' functions
451 This error indicates that the compiler found multiple functions with the
452 `#[start]` attribute. This is an error because there must be a unique entry
453 point into a Rust program. Example:
459 fn foo(argc: isize, argv: *const *const u8) -> isize { 0 } // ok!
463 // isn't thrown anymore
465 There are various restrictions on transmuting between types in Rust; for example
466 types being transmuted must have the same size. To apply all these restrictions,
467 the compiler must know the exact types that may be transmuted. When type
468 parameters are involved, this cannot always be done.
470 So, for example, the following is not allowed:
473 use std::mem::transmute;
475 struct Foo<T>(Vec<T>);
477 fn foo<T>(x: Vec<T>) {
478 // we are transmuting between Vec<T> and Foo<F> here
479 let y: Foo<T> = unsafe { transmute(x) };
480 // do something with y
484 In this specific case there's a good chance that the transmute is harmless (but
485 this is not guaranteed by Rust). However, when alignment and enum optimizations
486 come into the picture, it's quite likely that the sizes may or may not match
487 with different type parameter substitutions. It's not possible to check this for
488 _all_ possible types, so `transmute()` simply only accepts types without any
489 unsubstituted type parameters.
491 If you need this, there's a good chance you're doing something wrong. Keep in
492 mind that Rust doesn't guarantee much about the layout of different structs
493 (even two structs with identical declarations may have different layouts). If
494 there is a solution that avoids the transmute entirely, try it instead.
496 If it's possible, hand-monomorphize the code by writing the function for each
497 possible type substitution. It's possible to use traits to do this cleanly,
501 struct Foo<T>(Vec<T>);
503 trait MyTransmutableType {
504 fn transmute(Vec<Self>) -> Foo<Self>;
507 impl MyTransmutableType for u8 {
508 fn transmute(x: Foo<u8>) -> Vec<u8> {
513 impl MyTransmutableType for String {
514 fn transmute(x: Foo<String>) -> Vec<String> {
519 // ... more impls for the types you intend to transmute
521 fn foo<T: MyTransmutableType>(x: Vec<T>) {
522 let y: Foo<T> = <T as MyTransmutableType>::transmute(x);
523 // do something with y
527 Each impl will be checked for a size match in the transmute as usual, and since
528 there are no unbound type parameters involved, this should compile unless there
529 is a size mismatch in one of the impls.
531 It is also possible to manually transmute:
534 ptr::read(&v as *const _ as *const SomeType) // `v` transmuted to `SomeType`
537 Note that this does not move `v` (unlike `transmute`), and may need a
538 call to `mem::forget(v)` in case you want to avoid destructors being called.
542 A lang item was redefined.
544 Erroneous code example:
546 ```compile_fail,E0152
547 #![feature(lang_items)]
549 #[lang = "panic_fmt"]
550 struct Foo; // error: duplicate lang item found: `panic_fmt`
553 Lang items are already implemented in the standard library. Unless you are
554 writing a free-standing application (e.g. a kernel), you do not need to provide
557 You can build a free-standing crate by adding `#![no_std]` to the crate
564 See also https://doc.rust-lang.org/book/no-stdlib.html
568 An associated type binding was done outside of the type parameter declaration
569 and `where` clause. Erroneous code example:
571 ```compile_fail,E0229
574 fn boo(&self) -> <Self as Foo>::A;
581 fn boo(&self) -> usize { 42 }
584 fn baz<I>(x: &<I as Foo<A=Bar>>::A) {}
585 // error: associated type bindings are not allowed here
588 To solve this error, please move the type bindings in the type parameter
592 fn baz<I: Foo<A=Bar>>(x: &<I as Foo>::A) {} // ok!
595 Or in the `where` clause:
598 fn baz<I>(x: &<I as Foo>::A) where I: Foo<A=Bar> {}
603 When using a lifetime like `'a` in a type, it must be declared before being
606 These two examples illustrate the problem:
608 ```compile_fail,E0261
609 // error, use of undeclared lifetime name `'a`
610 fn foo(x: &'a str) { }
613 // error, use of undeclared lifetime name `'a`
618 These can be fixed by declaring lifetime parameters:
621 fn foo<'a>(x: &'a str) {}
630 Declaring certain lifetime names in parameters is disallowed. For example,
631 because the `'static` lifetime is a special built-in lifetime name denoting
632 the lifetime of the entire program, this is an error:
634 ```compile_fail,E0262
635 // error, invalid lifetime parameter name `'static`
636 fn foo<'static>(x: &'static str) { }
641 A lifetime name cannot be declared more than once in the same scope. For
644 ```compile_fail,E0263
645 // error, lifetime name `'a` declared twice in the same scope
646 fn foo<'a, 'b, 'a>(x: &'a str, y: &'b str) { }
651 An unknown external lang item was used. Erroneous code example:
653 ```compile_fail,E0264
654 #![feature(lang_items)]
657 #[lang = "cake"] // error: unknown external lang item: `cake`
662 A list of available external lang items is available in
663 `src/librustc/middle/weak_lang_items.rs`. Example:
666 #![feature(lang_items)]
669 #[lang = "panic_fmt"] // ok!
676 A returned value was expected but not all control paths return one.
678 Erroneous code example:
680 ```compile_fail,E0269
681 fn abracada_FAIL() -> String {
682 "this won't work".to_string();
683 // error: not all control paths return a value
687 In the previous code, the function is supposed to return a `String`, however,
688 the code returns nothing (because of the ';'). Another erroneous code would be:
691 fn abracada_FAIL(b: bool) -> u32 {
695 "a" // It fails because an `u32` was expected and something else is
701 It is advisable to find out what the unhandled cases are and check for them,
702 returning an appropriate value or panicking if necessary. Check if you need
703 to remove a semicolon from the last expression, like in the first erroneous
708 Rust lets you define functions which are known to never return, i.e. are
709 'diverging', by marking its return type as `!`.
711 For example, the following functions never return:
719 foo() // foo() is diverging, so this will diverge too
723 panic!(); // this macro internally expands to a call to a diverging function
727 Such functions can be used in a place where a value is expected without
728 returning a value of that type, for instance:
740 _ => foo() // diverging function called here
746 If the third arm of the match block is reached, since `foo()` doesn't ever
747 return control to the match block, it is fine to use it in a place where an
748 integer was expected. The `match` block will never finish executing, and any
749 point where `y` (like the print statement) is needed will not be reached.
751 However, if we had a diverging function that actually does finish execution:
759 Then we would have an unknown value for `y` in the following code:
777 In the previous example, the print statement was never reached when the
778 wildcard match arm was hit, so we were okay with `foo()` not returning an
779 integer that we could set to `y`. But in this example, `foo()` actually does
780 return control, so the print statement will be executed with an uninitialized
783 Obviously we cannot have functions which are allowed to be used in such
784 positions and yet can return control. So, if you are defining a function that
785 returns `!`, make sure that there is no way for it to actually finish
790 This is because of a type mismatch between the associated type of some
791 trait (e.g. `T::Bar`, where `T` implements `trait Quux { type Bar; }`)
792 and another type `U` that is required to be equal to `T::Bar`, but is not.
795 Here is a basic example:
797 ```compile_fail,E0271
798 trait Trait { type AssociatedType; }
800 fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
804 impl Trait for i8 { type AssociatedType = &'static str; }
809 Here is that same example again, with some explanatory comments:
812 trait Trait { type AssociatedType; }
814 fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
815 // ~~~~~~~~ ~~~~~~~~~~~~~~~~~~
817 // This says `foo` can |
818 // only be used with |
820 // implements `Trait`. |
822 // This says not only must
823 // `T` be an impl of `Trait`
824 // but also that the impl
825 // must assign the type `u32`
826 // to the associated type.
830 impl Trait for i8 { type AssociatedType = &'static str; }
831 ~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
836 // ... but it is an implementation
837 // that assigns `&'static str` to
838 // the associated type.
841 // Here, we invoke `foo` with an `i8`, which does not satisfy
842 // the constraint `<i8 as Trait>::AssociatedType=u32`, and
843 // therefore the type-checker complains with this error code.
846 Here is a more subtle instance of the same problem, that can
847 arise with for-loops in Rust:
850 let vs: Vec<i32> = vec![1, 2, 3, 4];
859 The above fails because of an analogous type mismatch,
860 though may be harder to see. Again, here are some
861 explanatory comments for the same example:
865 let vs = vec![1, 2, 3, 4];
867 // `for`-loops use a protocol based on the `Iterator`
868 // trait. Each item yielded in a `for` loop has the
869 // type `Iterator::Item` -- that is, `Item` is the
870 // associated type of the concrete iterator impl.
874 // | We borrow `vs`, iterating over a sequence of
875 // | *references* of type `&Elem` (where `Elem` is
876 // | vector's element type). Thus, the associated
877 // | type `Item` must be a reference `&`-type ...
879 // ... and `v` has the type `Iterator::Item`, as dictated by
880 // the `for`-loop protocol ...
886 // ... but *here*, `v` is forced to have some integral type;
887 // only types like `u8`,`i8`,`u16`,`i16`, et cetera can
888 // match the pattern `1` ...
893 // ... therefore, the compiler complains, because it sees
894 // an attempt to solve the equations
895 // `some integral-type` = type-of-`v`
896 // = `Iterator::Item`
897 // = `&Elem` (i.e. `some reference type`)
899 // which cannot possibly all be true.
905 To avoid those issues, you have to make the types match correctly.
906 So we can fix the previous examples like this:
910 trait Trait { type AssociatedType; }
912 fn foo<T>(t: T) where T: Trait<AssociatedType = &'static str> {
916 impl Trait for i8 { type AssociatedType = &'static str; }
921 let vs = vec![1, 2, 3, 4];
932 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
933 message for when a particular trait isn't implemented on a type placed in a
934 position that needs that trait. For example, when the following code is
938 #![feature(on_unimplemented)]
940 fn foo<T: Index<u8>>(x: T){}
942 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
943 trait Index<Idx> { /* ... */ }
945 foo(true); // `bool` does not implement `Index<u8>`
948 There will be an error about `bool` not implementing `Index<u8>`, followed by a
949 note saying "the type `bool` cannot be indexed by `u8`".
951 As you can see, you can specify type parameters in curly braces for
952 substitution with the actual types (using the regular format string syntax) in
953 a given situation. Furthermore, `{Self}` will substitute to the type (in this
954 case, `bool`) that we tried to use.
956 This error appears when the curly braces contain an identifier which doesn't
957 match with any of the type parameters or the string `Self`. This might happen
958 if you misspelled a type parameter, or if you intended to use literal curly
959 braces. If it is the latter, escape the curly braces with a second curly brace
960 of the same type; e.g. a literal `{` is `{{`.
964 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
965 message for when a particular trait isn't implemented on a type placed in a
966 position that needs that trait. For example, when the following code is
970 #![feature(on_unimplemented)]
972 fn foo<T: Index<u8>>(x: T){}
974 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
975 trait Index<Idx> { /* ... */ }
977 foo(true); // `bool` does not implement `Index<u8>`
980 there will be an error about `bool` not implementing `Index<u8>`, followed by a
981 note saying "the type `bool` cannot be indexed by `u8`".
983 As you can see, you can specify type parameters in curly braces for
984 substitution with the actual types (using the regular format string syntax) in
985 a given situation. Furthermore, `{Self}` will substitute to the type (in this
986 case, `bool`) that we tried to use.
988 This error appears when the curly braces do not contain an identifier. Please
989 add one of the same name as a type parameter. If you intended to use literal
990 braces, use `{{` and `}}` to escape them.
994 The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
995 message for when a particular trait isn't implemented on a type placed in a
996 position that needs that trait. For example, when the following code is
1000 #![feature(on_unimplemented)]
1002 fn foo<T: Index<u8>>(x: T){}
1004 #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1005 trait Index<Idx> { /* ... */ }
1007 foo(true); // `bool` does not implement `Index<u8>`
1010 there will be an error about `bool` not implementing `Index<u8>`, followed by a
1011 note saying "the type `bool` cannot be indexed by `u8`".
1013 For this to work, some note must be specified. An empty attribute will not do
1014 anything, please remove the attribute or add some helpful note for users of the
1019 This error occurs when there was a recursive trait requirement that overflowed
1020 before it could be evaluated. Often this means that there is unbounded
1021 recursion in resolving some type bounds.
1023 For example, in the following code:
1025 ```compile_fail,E0275
1030 impl<T> Foo for T where Bar<T>: Foo {}
1033 To determine if a `T` is `Foo`, we need to check if `Bar<T>` is `Foo`. However,
1034 to do this check, we need to determine that `Bar<Bar<T>>` is `Foo`. To
1035 determine this, we check if `Bar<Bar<Bar<T>>>` is `Foo`, and so on. This is
1036 clearly a recursive requirement that can't be resolved directly.
1038 Consider changing your trait bounds so that they're less self-referential.
1042 This error occurs when a bound in an implementation of a trait does not match
1043 the bounds specified in the original trait. For example:
1045 ```compile_fail,E0276
1051 fn foo<T>(x: T) where T: Copy {}
1055 Here, all types implementing `Foo` must have a method `foo<T>(x: T)` which can
1056 take any type `T`. However, in the `impl` for `bool`, we have added an extra
1057 bound that `T` is `Copy`, which isn't compatible with the original trait.
1059 Consider removing the bound from the method or adding the bound to the original
1060 method definition in the trait.
1064 You tried to use a type which doesn't implement some trait in a place which
1065 expected that trait. Erroneous code example:
1067 ```compile_fail,E0277
1068 // here we declare the Foo trait with a bar method
1073 // we now declare a function which takes an object implementing the Foo trait
1074 fn some_func<T: Foo>(foo: T) {
1079 // we now call the method with the i32 type, which doesn't implement
1081 some_func(5i32); // error: the trait bound `i32 : Foo` is not satisfied
1085 In order to fix this error, verify that the type you're using does implement
1093 fn some_func<T: Foo>(foo: T) {
1094 foo.bar(); // we can now use this method since i32 implements the
1098 // we implement the trait on the i32 type
1104 some_func(5i32); // ok!
1108 Or in a generic context, an erroneous code example would look like:
1110 ```compile_fail,E0277
1111 fn some_func<T>(foo: T) {
1112 println!("{:?}", foo); // error: the trait `core::fmt::Debug` is not
1113 // implemented for the type `T`
1117 // We now call the method with the i32 type,
1118 // which *does* implement the Debug trait.
1123 Note that the error here is in the definition of the generic function: Although
1124 we only call it with a parameter that does implement `Debug`, the compiler
1125 still rejects the function: It must work with all possible input types. In
1126 order to make this example compile, we need to restrict the generic type we're
1132 // Restrict the input type to types that implement Debug.
1133 fn some_func<T: fmt::Debug>(foo: T) {
1134 println!("{:?}", foo);
1138 // Calling the method is still fine, as i32 implements Debug.
1141 // This would fail to compile now:
1142 // struct WithoutDebug;
1143 // some_func(WithoutDebug);
1147 Rust only looks at the signature of the called function, as such it must
1148 already specify all requirements that will be used for every type parameter.
1152 You tried to supply a type which doesn't implement some trait in a location
1153 which expected that trait. This error typically occurs when working with
1154 `Fn`-based types. Erroneous code example:
1156 ```compile_fail,E0281
1157 fn foo<F: Fn()>(x: F) { }
1160 // type mismatch: the type ... implements the trait `core::ops::Fn<(_,)>`,
1161 // but the trait `core::ops::Fn<()>` is required (expected (), found tuple
1167 The issue in this case is that `foo` is defined as accepting a `Fn` with no
1168 arguments, but the closure we attempted to pass to it requires one argument.
1172 This error indicates that type inference did not result in one unique possible
1173 type, and extra information is required. In most cases this can be provided
1174 by adding a type annotation. Sometimes you need to specify a generic type
1177 A common example is the `collect` method on `Iterator`. It has a generic type
1178 parameter with a `FromIterator` bound, which for a `char` iterator is
1179 implemented by `Vec` and `String` among others. Consider the following snippet
1180 that reverses the characters of a string:
1182 ```compile_fail,E0282
1183 let x = "hello".chars().rev().collect();
1186 In this case, the compiler cannot infer what the type of `x` should be:
1187 `Vec<char>` and `String` are both suitable candidates. To specify which type to
1188 use, you can use a type annotation on `x`:
1191 let x: Vec<char> = "hello".chars().rev().collect();
1194 It is not necessary to annotate the full type. Once the ambiguity is resolved,
1195 the compiler can infer the rest:
1198 let x: Vec<_> = "hello".chars().rev().collect();
1201 Another way to provide the compiler with enough information, is to specify the
1202 generic type parameter:
1205 let x = "hello".chars().rev().collect::<Vec<char>>();
1208 Again, you need not specify the full type if the compiler can infer it:
1211 let x = "hello".chars().rev().collect::<Vec<_>>();
1214 Apart from a method or function with a generic type parameter, this error can
1215 occur when a type parameter of a struct or trait cannot be inferred. In that
1216 case it is not always possible to use a type annotation, because all candidates
1217 have the same return type. For instance:
1219 ```compile_fail,E0282
1230 let number = Foo::bar();
1235 This will fail because the compiler does not know which instance of `Foo` to
1236 call `bar` on. Change `Foo::bar()` to `Foo::<T>::bar()` to resolve the error.
1240 This error occurs when the compiler doesn't have enough information
1241 to unambiguously choose an implementation.
1245 ```compile_fail,E0283
1252 impl Generator for Impl {
1253 fn create() -> u32 { 1 }
1258 impl Generator for AnotherImpl {
1259 fn create() -> u32 { 2 }
1263 let cont: u32 = Generator::create();
1264 // error, impossible to choose one of Generator trait implementation
1265 // Impl or AnotherImpl? Maybe anything else?
1269 To resolve this error use the concrete type:
1278 impl Generator for AnotherImpl {
1279 fn create() -> u32 { 2 }
1283 let gen1 = AnotherImpl::create();
1285 // if there are multiple methods with same name (different traits)
1286 let gen2 = <AnotherImpl as Generator>::create();
1292 This error indicates that the given recursion limit could not be parsed. Ensure
1293 that the value provided is a positive integer between quotes.
1295 Erroneous code example:
1297 ```compile_fail,E0296
1303 And a working example:
1306 #![recursion_limit="1000"]
1313 This error occurs when the compiler was unable to infer the concrete type of a
1314 variable. It can occur for several cases, the most common of which is a
1315 mismatch in the expected type that the compiler inferred for a variable's
1316 initializing expression, and the actual type explicitly assigned to the
1321 ```compile_fail,E0308
1322 let x: i32 = "I am not a number!";
1323 // ~~~ ~~~~~~~~~~~~~~~~~~~~
1325 // | initializing expression;
1326 // | compiler infers type `&str`
1328 // type `i32` assigned to variable `x`
1331 Another situation in which this occurs is when you attempt to use the `try!`
1332 macro inside a function that does not return a `Result<T, E>`:
1334 ```compile_fail,E0308
1338 let mut f = try!(File::create("foo.txt"));
1342 This code gives an error like this:
1345 <std macros>:5:8: 6:42 error: mismatched types:
1347 found `core::result::Result<_, _>`
1349 found enum `core::result::Result`) [E0308]
1352 `try!` returns a `Result<T, E>`, and so the function must. But `main()` has
1353 `()` as its return type, hence the error.
1357 Types in type definitions have lifetimes associated with them that represent
1358 how long the data stored within them is guaranteed to be live. This lifetime
1359 must be as long as the data needs to be alive, and missing the constraint that
1360 denotes this will cause this error.
1362 ```compile_fail,E0309
1363 // This won't compile because T is not constrained, meaning the data
1364 // stored in it is not guaranteed to last as long as the reference
1370 This will compile, because it has the constraint on the type parameter:
1373 struct Foo<'a, T: 'a> {
1380 Types in type definitions have lifetimes associated with them that represent
1381 how long the data stored within them is guaranteed to be live. This lifetime
1382 must be as long as the data needs to be alive, and missing the constraint that
1383 denotes this will cause this error.
1385 ```compile_fail,E0310
1386 // This won't compile because T is not constrained to the static lifetime
1387 // the reference needs
1393 This will compile, because it has the constraint on the type parameter:
1396 struct Foo<T: 'static> {
1403 A lifetime of reference outlives lifetime of borrowed content.
1405 Erroneous code example:
1407 ```compile_fail,E0312
1408 fn make_child<'human, 'elve>(x: &mut &'human isize, y: &mut &'elve isize) {
1410 // error: lifetime of reference outlives lifetime of borrowed content
1414 The compiler cannot determine if the `human` lifetime will live long enough
1415 to keep up on the elve one. To solve this error, you have to give an
1416 explicit lifetime hierarchy:
1419 fn make_child<'human, 'elve: 'human>(x: &mut &'human isize,
1420 y: &mut &'elve isize) {
1425 Or use the same lifetime for every variable:
1428 fn make_child<'elve>(x: &mut &'elve isize, y: &mut &'elve isize) {
1435 In Rust 1.3, the default object lifetime bounds are expected to change, as
1436 described in RFC #1156 [1]. You are getting a warning because the compiler
1437 thinks it is possible that this change will cause a compilation error in your
1438 code. It is possible, though unlikely, that this is a false alarm.
1440 The heart of the change is that where `&'a Box<SomeTrait>` used to default to
1441 `&'a Box<SomeTrait+'a>`, it now defaults to `&'a Box<SomeTrait+'static>` (here,
1442 `SomeTrait` is the name of some trait type). Note that the only types which are
1443 affected are references to boxes, like `&Box<SomeTrait>` or
1444 `&[Box<SomeTrait>]`. More common types like `&SomeTrait` or `Box<SomeTrait>`
1447 To silence this warning, edit your code to use an explicit bound. Most of the
1448 time, this means that you will want to change the signature of a function that
1449 you are calling. For example, if the error is reported on a call like `foo(x)`,
1450 and `foo` is defined as follows:
1453 fn foo(arg: &Box<SomeTrait>) { ... }
1456 You might change it to:
1459 fn foo<'a>(arg: &Box<SomeTrait+'a>) { ... }
1462 This explicitly states that you expect the trait object `SomeTrait` to contain
1463 references (with a maximum lifetime of `'a`).
1465 [1]: https://github.com/rust-lang/rfcs/pull/1156
1469 An invalid lint attribute has been given. Erroneous code example:
1471 ```compile_fail,E0452
1472 #![allow(foo = "")] // error: malformed lint attribute
1475 Lint attributes only accept a list of identifiers (where each identifier is a
1476 lint name). Ensure the attribute is of this form:
1479 #![allow(foo)] // ok!
1481 #![allow(foo, foo2)] // ok!
1486 A lint check attribute was overruled by a `forbid` directive set as an
1487 attribute on an enclosing scope, or on the command line with the `-F` option.
1489 Example of erroneous code:
1491 ```compile_fail,E0453
1492 #![forbid(non_snake_case)]
1494 #[allow(non_snake_case)]
1496 let MyNumber = 2; // error: allow(non_snake_case) overruled by outer
1497 // forbid(non_snake_case)
1501 The `forbid` lint setting, like `deny`, turns the corresponding compiler
1502 warning into a hard error. Unlike `deny`, `forbid` prevents itself from being
1503 overridden by inner attributes.
1505 If you're sure you want to override the lint check, you can change `forbid` to
1506 `deny` (or use `-D` instead of `-F` if the `forbid` setting was given as a
1507 command-line option) to allow the inner lint check attribute:
1510 #![deny(non_snake_case)]
1512 #[allow(non_snake_case)]
1514 let MyNumber = 2; // ok!
1518 Otherwise, edit the code to pass the lint check, and remove the overruled
1522 #![forbid(non_snake_case)]
1531 A lifetime name is shadowing another lifetime name. Erroneous code example:
1533 ```compile_fail,E0496
1539 fn f<'a>(x: &'a i32) { // error: lifetime name `'a` shadows a lifetime
1540 // name that is already in scope
1545 Please change the name of one of the lifetimes to remove this error. Example:
1553 fn f<'b>(x: &'b i32) { // ok!
1563 A stability attribute was used outside of the standard library. Erroneous code
1567 #[stable] // error: stability attributes may not be used outside of the
1572 It is not possible to use stability attributes outside of the standard library.
1573 Also, for now, it is not possible to write deprecation messages either.
1577 Transmute with two differently sized types was attempted. Erroneous code
1580 ```compile_fail,E0512
1581 fn takes_u8(_: u8) {}
1584 unsafe { takes_u8(::std::mem::transmute(0u16)); }
1585 // error: transmute called with differently sized types
1589 Please use types with same size or use the expected type directly. Example:
1592 fn takes_u8(_: u8) {}
1595 unsafe { takes_u8(::std::mem::transmute(0i8)); } // ok!
1597 unsafe { takes_u8(0u8); } // ok!
1603 This error indicates that a `#[repr(..)]` attribute was placed on an
1606 Examples of erroneous code:
1608 ```compile_fail,E0517
1616 struct Foo {bar: bool, baz: bool}
1624 * The `#[repr(C)]` attribute can only be placed on structs and enums.
1625 * The `#[repr(packed)]` and `#[repr(simd)]` attributes only work on structs.
1626 * The `#[repr(u8)]`, `#[repr(i16)]`, etc attributes only work on enums.
1628 These attributes do not work on typedefs, since typedefs are just aliases.
1630 Representations like `#[repr(u8)]`, `#[repr(i64)]` are for selecting the
1631 discriminant size for C-like enums (when there is no associated data, e.g.
1632 `enum Color {Red, Blue, Green}`), effectively setting the size of the enum to
1633 the size of the provided type. Such an enum can be cast to a value of the same
1634 type as well. In short, `#[repr(u8)]` makes the enum behave like an integer
1635 with a constrained set of allowed values.
1637 Only C-like enums can be cast to numerical primitives, so this attribute will
1638 not apply to structs.
1640 `#[repr(packed)]` reduces padding to make the struct size smaller. The
1641 representation of enums isn't strictly defined in Rust, and this attribute
1642 won't work on enums.
1644 `#[repr(simd)]` will give a struct consisting of a homogenous series of machine
1645 types (i.e. `u8`, `i32`, etc) a representation that permits vectorization via
1646 SIMD. This doesn't make much sense for enums since they don't consist of a
1647 single list of data.
1651 This error indicates that an `#[inline(..)]` attribute was incorrectly placed
1652 on something other than a function or method.
1654 Examples of erroneous code:
1656 ```compile_fail,E0518
1666 `#[inline]` hints the compiler whether or not to attempt to inline a method or
1667 function. By default, the compiler does a pretty good job of figuring this out
1668 itself, but if you feel the need for annotations, `#[inline(always)]` and
1669 `#[inline(never)]` can override or force the compiler's decision.
1671 If you wish to apply this attribute to all methods in an impl, manually annotate
1672 each method; it is not possible to annotate the entire impl with an `#[inline]`
1677 The lang attribute is intended for marking special items that are built-in to
1678 Rust itself. This includes special traits (like `Copy` and `Sized`) that affect
1679 how the compiler behaves, as well as special functions that may be automatically
1680 invoked (such as the handler for out-of-bounds accesses when indexing a slice).
1681 Erroneous code example:
1683 ```compile_fail,E0522
1684 #![feature(lang_items)]
1687 fn cookie() -> ! { // error: definition of an unknown language item: `cookie`
1696 register_diagnostics
! {
1697 // E0006 // merged with E0005
1700 E0278
, // requirement is not satisfied
1701 E0279
, // requirement is not satisfied
1702 E0280
, // requirement is not satisfied
1703 E0284
, // cannot resolve type
1704 // E0285, // overflow evaluation builtin bounds
1705 // E0300, // unexpanded macro
1706 // E0304, // expected signed integer constant
1707 // E0305, // expected constant
1708 E0311
, // thing may not live long enough
1709 E0313
, // lifetime of borrowed pointer outlives lifetime of captured variable
1710 E0314
, // closure outlives stack frame
1711 E0315
, // cannot invoke closure outside of its lifetime
1712 E0316
, // nested quantification of lifetimes
1713 E0473
, // dereference of reference outside its lifetime
1714 E0474
, // captured variable `..` does not outlive the enclosing closure
1715 E0475
, // index of slice outside its lifetime
1716 E0476
, // lifetime of the source pointer does not outlive lifetime bound...
1717 E0477
, // the type `..` does not fulfill the required lifetime...
1718 E0478
, // lifetime bound not satisfied
1719 E0479
, // the type `..` (provided as the value of a type parameter) is...
1720 E0480
, // lifetime of method receiver does not outlive the method call
1721 E0481
, // lifetime of function argument does not outlive the function call
1722 E0482
, // lifetime of return value does not outlive the function call
1723 E0483
, // lifetime of operand does not outlive the operation
1724 E0484
, // reference is not valid at the time of borrow
1725 E0485
, // automatically reference is not valid at the time of borrow
1726 E0486
, // type of expression contains references that are not valid during...
1727 E0487
, // unsafe use of destructor: destructor might be called while...
1728 E0488
, // lifetime of variable does not enclose its declaration
1729 E0489
, // type/lifetime parameter not in scope here
1730 E0490
, // a value of type `..` is borrowed for too long
1731 E0491
, // in type `..`, reference has a longer lifetime than the data it...
1732 E0495
, // cannot infer an appropriate lifetime due to conflicting requirements
1733 E0525
// expected a closure that implements `..` but this closure only implements `..`