1 #![allow(non_snake_case)]
3 register_long_diagnostics! {
6 A pattern used to match against an enum variant must provide a sub-pattern for
7 each field of the enum variant. This error indicates that a pattern attempted to
8 extract an incorrect number of fields from a variant.
12 Apple(String, String),
17 Here the `Apple` variant has two fields, and should be matched against like so:
21 Apple(String, String),
25 let x = Fruit::Apple(String::new(), String::new());
29 Fruit::Apple(a, b) => {},
34 Matching with the wrong number of fields has no sensible interpretation:
38 Apple(String, String),
42 let x = Fruit::Apple(String::new(), String::new());
46 Fruit::Apple(a) => {},
47 Fruit::Apple(a, b, c) => {},
51 Check how many fields the enum was declared with and ensure that your pattern
56 Each field of a struct can only be bound once in a pattern. Erroneous code
66 let x = Foo { a:1, b:2 };
68 let Foo { a: x, a: y } = x;
69 // error: field `a` bound multiple times in the pattern
73 Each occurrence of a field name binds the value of that field, so to fix this
74 error you will have to remove or alter the duplicate uses of the field name.
75 Perhaps you misspelled another field name? Example:
84 let x = Foo { a:1, b:2 };
86 let Foo { a: x, b: y } = x; // ok!
92 This error indicates that a struct pattern attempted to extract a non-existent
93 field from a struct. Struct fields are identified by the name used before the
94 colon `:` so struct patterns should resemble the declaration of the struct type
104 let thing = Thing { x: 1, y: 2 };
107 Thing { x: xfield, y: yfield } => {}
111 If you are using shorthand field patterns but want to refer to the struct field
112 by a different name, you should rename it explicitly.
116 ```compile_fail,E0026
122 let thing = Thing { x: 0, y: 0 };
137 let thing = Thing { x: 0, y: 0 };
140 Thing { x, y: z } => {}
146 This error indicates that a pattern for a struct fails to specify a sub-pattern
147 for every one of the struct's fields. Ensure that each field from the struct's
148 definition is mentioned in the pattern, or use `..` to ignore unwanted fields.
152 ```compile_fail,E0027
158 let d = Dog { name: "Rusty".to_string(), age: 8 };
160 // This is incorrect.
166 This is correct (explicit):
174 let d = Dog { name: "Rusty".to_string(), age: 8 };
177 Dog { name: ref n, age: x } => {}
180 // This is also correct (ignore unused fields).
182 Dog { age: x, .. } => {}
188 In a match expression, only numbers and characters can be matched against a
189 range. This is because the compiler checks that the range is non-empty at
190 compile-time, and is unable to evaluate arbitrary comparison functions. If you
191 want to capture values of an orderable type between two end-points, you can use
194 ```compile_fail,E0029
195 let string = "salutations !";
197 // The ordering relation for strings can't be evaluated at compile time,
198 // so this doesn't work:
200 "hello" ..= "world" => {}
204 // This is a more general version, using a guard:
206 s if s >= "hello" && s <= "world" => {}
213 This error indicates that a pointer to a trait type cannot be implicitly
214 dereferenced by a pattern. Every trait defines a type, but because the
215 size of trait implementors isn't fixed, this type has no compile-time size.
216 Therefore, all accesses to trait types must be through pointers. If you
217 encounter this error you should try to avoid dereferencing the pointer.
219 ```compile_fail,E0033
220 # trait SomeTrait { fn method_one(&self){} fn method_two(&self){} }
221 # impl<T> SomeTrait for T {}
222 let trait_obj: &SomeTrait = &"some_value";
224 // This tries to implicitly dereference to create an unsized local variable.
225 let &invalid = trait_obj;
227 // You can call methods without binding to the value being pointed at.
228 trait_obj.method_one();
229 trait_obj.method_two();
232 You can read more about trait objects in the [Trait Objects] section of the
235 [Trait Objects]: https://doc.rust-lang.org/reference/types.html#trait-objects
239 The compiler doesn't know what method to call because more than one method
240 has the same prototype. Erroneous code example:
242 ```compile_fail,E0034
253 impl Trait1 for Test { fn foo() {} }
254 impl Trait2 for Test { fn foo() {} }
257 Test::foo() // error, which foo() to call?
261 To avoid this error, you have to keep only one of them and remove the others.
262 So let's take our example and fix it:
271 impl Trait1 for Test { fn foo() {} }
274 Test::foo() // and now that's good!
278 However, a better solution would be using fully explicit naming of type and
292 impl Trait1 for Test { fn foo() {} }
293 impl Trait2 for Test { fn foo() {} }
296 <Test as Trait1>::foo()
313 impl F for X { fn m(&self) { println!("I am F"); } }
314 impl G for X { fn m(&self) { println!("I am G"); } }
319 F::m(&f); // it displays "I am F"
320 G::m(&f); // it displays "I am G"
326 It is not allowed to manually call destructors in Rust. It is also not
327 necessary to do this since `drop` is called automatically whenever a value goes
330 Here's an example of this error:
332 ```compile_fail,E0040
344 let mut x = Foo { x: -7 };
345 x.drop(); // error: explicit use of destructor method
351 You can't use type parameters on foreign items. Example of erroneous code:
353 ```compile_fail,E0044
354 extern { fn some_func<T>(x: T); }
357 To fix this, replace the type parameter with the specializations that you
361 extern { fn some_func_i32(x: i32); }
362 extern { fn some_func_i64(x: i64); }
367 Rust only supports variadic parameters for interoperability with C code in its
368 FFI. As such, variadic parameters can only be used with functions which are
369 using the C ABI. Examples of erroneous code:
372 #![feature(unboxed_closures)]
374 extern "rust-call" { fn foo(x: u8, ...); }
378 fn foo(x: u8, ...) {}
381 To fix such code, put them in an extern "C" block:
391 Items are missing in a trait implementation. Erroneous code example:
393 ```compile_fail,E0046
401 // error: not all trait items implemented, missing: `foo`
404 When trying to make some type implement a trait `Foo`, you must, at minimum,
405 provide implementations for all of `Foo`'s required methods (meaning the
406 methods that do not have default implementations), as well as any required
407 trait items like associated types or constants. Example:
423 This error indicates that an attempted implementation of a trait method
424 has the wrong number of type parameters.
426 For example, the trait below has a method `foo` with a type parameter `T`,
427 but the implementation of `foo` for the type `Bar` is missing this parameter:
429 ```compile_fail,E0049
431 fn foo<T: Default>(x: T) -> Self;
436 // error: method `foo` has 0 type parameters but its trait declaration has 1
439 fn foo(x: bool) -> Self { Bar }
445 This error indicates that an attempted implementation of a trait method
446 has the wrong number of function parameters.
448 For example, the trait below has a method `foo` with two function parameters
449 (`&self` and `u8`), but the implementation of `foo` for the type `Bar` omits
452 ```compile_fail,E0050
454 fn foo(&self, x: u8) -> bool;
459 // error: method `foo` has 1 parameter but the declaration in trait `Foo::foo`
462 fn foo(&self) -> bool { true }
468 The parameters of any trait method must match between a trait implementation
469 and the trait definition.
471 Here are a couple examples of this error:
473 ```compile_fail,E0053
482 // error, expected u16, found i16
485 // error, types differ in mutability
486 fn bar(&mut self) { }
492 It is not allowed to cast to a bool. If you are trying to cast a numeric type
493 to a bool, you can compare it with zero instead:
495 ```compile_fail,E0054
498 // Not allowed, won't compile
499 let x_is_nonzero = x as bool;
506 let x_is_nonzero = x != 0;
511 During a method call, a value is automatically dereferenced as many times as
512 needed to make the value's type match the method's receiver. The catch is that
513 the compiler will only attempt to dereference a number of times up to the
514 recursion limit (which can be set via the `recursion_limit` attribute).
516 For a somewhat artificial example:
518 ```compile_fail,E0055
519 #![recursion_limit="2"]
531 // error, reached the recursion limit while auto-dereferencing `&&Foo`
536 One fix may be to increase the recursion limit. Note that it is possible to
537 create an infinite recursion of dereferencing, in which case the only fix is to
538 somehow break the recursion.
542 When invoking closures or other implementations of the function traits `Fn`,
543 `FnMut` or `FnOnce` using call notation, the number of parameters passed to the
544 function must match its definition.
546 An example using a closure:
548 ```compile_fail,E0057
550 let a = f(); // invalid, too few parameters
551 let b = f(4); // this works!
552 let c = f(2, 3); // invalid, too many parameters
555 A generic function must be treated similarly:
558 fn foo<F: Fn()>(f: F) {
559 f(); // this is valid, but f(3) would not work
565 The built-in function traits are generic over a tuple of the function arguments.
566 If one uses angle-bracket notation (`Fn<(T,), Output=U>`) instead of parentheses
567 (`Fn(T) -> U`) to denote the function trait, the type parameter should be a
568 tuple. Otherwise function call notation cannot be used and the trait will not be
569 implemented by closures.
571 The most likely source of this error is using angle-bracket notation without
572 wrapping the function argument type into a tuple, for example:
574 ```compile_fail,E0059
575 #![feature(unboxed_closures)]
577 fn foo<F: Fn<i32>>(f: F) -> F::Output { f(3) }
580 It can be fixed by adjusting the trait bound like this:
583 #![feature(unboxed_closures)]
585 fn foo<F: Fn<(i32,)>>(f: F) -> F::Output { f(3) }
588 Note that `(T,)` always denotes the type of a 1-tuple containing an element of
589 type `T`. The comma is necessary for syntactic disambiguation.
593 External C functions are allowed to be variadic. However, a variadic function
594 takes a minimum number of arguments. For example, consider C's variadic `printf`
598 use std::os::raw::{c_char, c_int};
601 fn printf(_: *const c_char, ...) -> c_int;
605 Using this declaration, it must be called with at least one argument, so
606 simply calling `printf()` is invalid. But the following uses are allowed:
609 # #![feature(static_nobundle)]
610 # use std::os::raw::{c_char, c_int};
611 # #[cfg_attr(all(windows, target_env = "msvc"),
612 # link(name = "legacy_stdio_definitions", kind = "static-nobundle"))]
613 # extern "C" { fn printf(_: *const c_char, ...) -> c_int; }
616 use std::ffi::CString;
618 let fmt = CString::new("test\n").unwrap();
619 printf(fmt.as_ptr());
621 let fmt = CString::new("number = %d\n").unwrap();
622 printf(fmt.as_ptr(), 3);
624 let fmt = CString::new("%d, %d\n").unwrap();
625 printf(fmt.as_ptr(), 10, 5);
630 // ^ Note: On MSVC 2015, the `printf` function is "inlined" in the C code, and
631 // the C runtime does not contain the `printf` definition. This leads to linker
632 // error from the doc test (issue #42830).
633 // This can be fixed by linking to the static library
634 // `legacy_stdio_definitions.lib` (see https://stackoverflow.com/a/36504365/).
635 // If this compatibility library is removed in the future, consider changing
636 // `printf` in this example to another well-known variadic function.
639 The number of arguments passed to a function must match the number of arguments
640 specified in the function signature.
642 For example, a function like:
645 fn f(a: u16, b: &str) {}
648 Must always be called with exactly two arguments, e.g., `f(2, "test")`.
650 Note that Rust does not have a notion of optional function arguments or
651 variadic functions (except for its C-FFI).
655 This error indicates that during an attempt to build a struct or struct-like
656 enum variant, one of the fields was specified more than once. Erroneous code
659 ```compile_fail,E0062
667 x: 0, // error: field `x` specified more than once
672 Each field should be specified exactly one time. Example:
680 let x = Foo { x: 0 }; // ok!
686 This error indicates that during an attempt to build a struct or struct-like
687 enum variant, one of the fields was not provided. Erroneous code example:
689 ```compile_fail,E0063
696 let x = Foo { x: 0 }; // error: missing field: `y`
700 Each field should be specified exactly once. Example:
709 let x = Foo { x: 0, y: 0 }; // ok!
715 The left-hand side of a compound assignment expression must be a place
716 expression. A place expression represents a memory location and includes
717 item paths (ie, namespaced variables), dereferences, indexing expressions,
718 and field references.
720 Let's start with some erroneous code examples:
722 ```compile_fail,E0067
723 use std::collections::LinkedList;
725 // Bad: assignment to non-place expression
726 LinkedList::new() += 1;
730 fn some_func(i: &mut i32) {
731 i += 12; // Error : '+=' operation cannot be applied on a reference !
735 And now some working examples:
744 fn some_func(i: &mut i32) {
751 The compiler found a function whose body contains a `return;` statement but
752 whose return type is not `()`. An example of this is:
754 ```compile_fail,E0069
761 Since `return;` is just like `return ();`, there is a mismatch between the
762 function's return type and the value being returned.
766 The left-hand side of an assignment operator must be a place expression. An
767 place expression represents a memory location and can be a variable (with
768 optional namespacing), a dereference, an indexing expression or a field
771 More details can be found in the [Expressions] section of the Reference.
773 [Expressions]: https://doc.rust-lang.org/reference/expressions.html#places-rvalues-and-temporaries
775 Now, we can go further. Here are some erroneous code examples:
777 ```compile_fail,E0070
783 const SOME_CONST : i32 = 12;
785 fn some_other_func() {}
788 SOME_CONST = 14; // error : a constant value cannot be changed!
789 1 = 3; // error : 1 isn't a valid place!
790 some_other_func() = 4; // error : we can't assign value to a function!
791 SomeStruct.x = 12; // error : SomeStruct a structure name but it is used
796 And now let's give working examples:
803 let mut s = SomeStruct {x: 0, y: 0};
805 s.x = 3; // that's good !
809 fn some_func(x: &mut i32) {
810 *x = 12; // that's good !
816 You tried to use structure-literal syntax to create an item that is
817 not a structure or enum variant.
819 Example of erroneous code:
821 ```compile_fail,E0071
823 let t = U32 { value: 4 }; // error: expected struct, variant or union type,
824 // found builtin type `u32`
827 To fix this, ensure that the name was correctly spelled, and that
828 the correct form of initializer was used.
830 For example, the code above can be fixed to:
838 let u = Foo::FirstValue(0i32);
846 #### Note: this error code is no longer emitted by the compiler.
848 You cannot define a struct (or enum) `Foo` that requires an instance of `Foo`
849 in order to make a new `Foo` value. This is because there would be no way a
850 first instance of `Foo` could be made to initialize another instance!
852 Here's an example of a struct that has this problem:
855 struct Foo { x: Box<Foo> } // error
858 One fix is to use `Option`, like so:
861 struct Foo { x: Option<Box<Foo>> }
864 Now it's possible to create at least one instance of `Foo`: `Foo { x: None }`.
868 #### Note: this error code is no longer emitted by the compiler.
870 When using the `#[simd]` attribute on a tuple struct, the components of the
871 tuple struct must all be of a concrete, nongeneric type so the compiler can
872 reason about how to use SIMD with them. This error will occur if the types
875 This will cause an error:
878 #![feature(repr_simd)]
881 struct Bad<T>(T, T, T);
887 #![feature(repr_simd)]
890 struct Good(u32, u32, u32);
895 The `#[simd]` attribute can only be applied to non empty tuple structs, because
896 it doesn't make sense to try to use SIMD operations when there are no values to
899 This will cause an error:
901 ```compile_fail,E0075
902 #![feature(repr_simd)]
911 #![feature(repr_simd)]
919 When using the `#[simd]` attribute to automatically use SIMD operations in tuple
920 struct, the types in the struct must all be of the same type, or the compiler
921 will trigger this error.
923 This will cause an error:
925 ```compile_fail,E0076
926 #![feature(repr_simd)]
929 struct Bad(u16, u32, u32);
935 #![feature(repr_simd)]
938 struct Good(u32, u32, u32);
943 When using the `#[simd]` attribute on a tuple struct, the elements in the tuple
944 must be machine types so SIMD operations can be applied to them.
946 This will cause an error:
948 ```compile_fail,E0077
949 #![feature(repr_simd)]
958 #![feature(repr_simd)]
961 struct Good(u32, u32, u32);
966 Enum discriminants are used to differentiate enum variants stored in memory.
967 This error indicates that the same value was used for two or more variants,
968 making them impossible to tell apart.
970 ```compile_fail,E0081
988 Note that variants without a manually specified discriminant are numbered from
989 top to bottom starting from 0, so clashes can occur with seemingly unrelated
992 ```compile_fail,E0081
999 Here `X` will have already been specified the discriminant 0 by the time `Y` is
1000 encountered, so a conflict occurs.
1004 An unsupported representation was attempted on a zero-variant enum.
1006 Erroneous code example:
1008 ```compile_fail,E0084
1010 enum NightsWatch {} // error: unsupported representation for zero-variant enum
1013 It is impossible to define an integer type to be used to represent zero-variant
1014 enum values because there are no zero-variant enum values. There is no way to
1015 construct an instance of the following type using only safe code. So you have
1016 two solutions. Either you add variants in your enum:
1026 or you remove the integer represention of your enum:
1034 #### Note: this error code is no longer emitted by the compiler.
1036 Too many type arguments were supplied for a function. For example:
1038 ```compile_fail,E0107
1042 foo::<f64, bool>(); // error: wrong number of type arguments:
1043 // expected 1, found 2
1047 The number of supplied arguments must exactly match the number of defined type
1052 #### Note: this error code is no longer emitted by the compiler.
1054 You gave too many lifetime arguments. Erroneous code example:
1056 ```compile_fail,E0107
1060 f::<'static>() // error: wrong number of lifetime arguments:
1061 // expected 0, found 1
1065 Please check you give the right number of lifetime arguments. Example:
1075 It's also important to note that the Rust compiler can generally
1076 determine the lifetime by itself. Example:
1084 // it can be written like this
1085 fn get_value<'a>(&'a self) -> &'a str { &self.value }
1086 // but the compiler works fine with this too:
1087 fn without_lifetime(&self) -> &str { &self.value }
1091 let f = Foo { value: "hello".to_owned() };
1093 println!("{}", f.get_value());
1094 println!("{}", f.without_lifetime());
1100 #### Note: this error code is no longer emitted by the compiler.
1102 Too few type arguments were supplied for a function. For example:
1104 ```compile_fail,E0107
1108 foo::<f64>(); // error: wrong number of type arguments: expected 2, found 1
1112 Note that if a function takes multiple type arguments but you want the compiler
1113 to infer some of them, you can use type placeholders:
1115 ```compile_fail,E0107
1116 fn foo<T, U>(x: T) {}
1120 foo::<f64>(x); // error: wrong number of type arguments:
1121 // expected 2, found 1
1122 foo::<_, f64>(x); // same as `foo::<bool, f64>(x)`
1128 #### Note: this error code is no longer emitted by the compiler.
1130 You gave too few lifetime arguments. Example:
1132 ```compile_fail,E0107
1133 fn foo<'a: 'b, 'b: 'a>() {}
1136 foo::<'static>(); // error: wrong number of lifetime arguments:
1137 // expected 2, found 1
1141 Please check you give the right number of lifetime arguments. Example:
1144 fn foo<'a: 'b, 'b: 'a>() {}
1147 foo::<'static, 'static>();
1153 You gave an unnecessary type parameter in a type alias. Erroneous code
1156 ```compile_fail,E0091
1157 type Foo<T> = u32; // error: type parameter `T` is unused
1159 type Foo<A,B> = Box<A>; // error: type parameter `B` is unused
1162 Please check you didn't write too many type parameters. Example:
1165 type Foo = u32; // ok!
1166 type Foo2<A> = Box<A>; // ok!
1171 You tried to declare an undefined atomic operation function.
1172 Erroneous code example:
1174 ```compile_fail,E0092
1175 #![feature(intrinsics)]
1177 extern "rust-intrinsic" {
1178 fn atomic_foo(); // error: unrecognized atomic operation
1183 Please check you didn't make a mistake in the function's name. All intrinsic
1184 functions are defined in librustc_codegen_llvm/intrinsic.rs and in
1185 libcore/intrinsics.rs in the Rust source code. Example:
1188 #![feature(intrinsics)]
1190 extern "rust-intrinsic" {
1191 fn atomic_fence(); // ok!
1197 You declared an unknown intrinsic function. Erroneous code example:
1199 ```compile_fail,E0093
1200 #![feature(intrinsics)]
1202 extern "rust-intrinsic" {
1203 fn foo(); // error: unrecognized intrinsic function: `foo`
1213 Please check you didn't make a mistake in the function's name. All intrinsic
1214 functions are defined in librustc_codegen_llvm/intrinsic.rs and in
1215 libcore/intrinsics.rs in the Rust source code. Example:
1218 #![feature(intrinsics)]
1220 extern "rust-intrinsic" {
1221 fn atomic_fence(); // ok!
1233 You gave an invalid number of type parameters to an intrinsic function.
1234 Erroneous code example:
1236 ```compile_fail,E0094
1237 #![feature(intrinsics)]
1239 extern "rust-intrinsic" {
1240 fn size_of<T, U>() -> usize; // error: intrinsic has wrong number
1241 // of type parameters
1245 Please check that you provided the right number of type parameters
1246 and verify with the function declaration in the Rust source code.
1250 #![feature(intrinsics)]
1252 extern "rust-intrinsic" {
1253 fn size_of<T>() -> usize; // ok!
1259 This error means that an incorrect number of generic arguments were provided:
1261 ```compile_fail,E0107
1262 struct Foo<T> { x: T }
1264 struct Bar { x: Foo } // error: wrong number of type arguments:
1265 // expected 1, found 0
1266 struct Baz<S, T> { x: Foo<S, T> } // error: wrong number of type arguments:
1267 // expected 1, found 2
1269 fn foo<T, U>(x: T, y: U) {}
1273 foo::<bool>(x); // error: wrong number of type arguments:
1274 // expected 2, found 1
1275 foo::<bool, i32, i32>(x, 2, 4); // error: wrong number of type arguments:
1276 // expected 2, found 3
1282 f::<'static>(); // error: wrong number of lifetime arguments:
1283 // expected 0, found 1
1290 You tried to give a type parameter to a type which doesn't need it. Erroneous
1293 ```compile_fail,E0109
1294 type X = u32<i32>; // error: type arguments are not allowed on this entity
1297 Please check that you used the correct type and recheck its definition. Perhaps
1298 it doesn't need the type parameter.
1303 type X = u32; // this compiles
1306 Note that type parameters for enum-variant constructors go after the variant,
1307 not after the enum (`Option::None::<u32>`, not `Option::<u32>::None`).
1311 You tried to give a lifetime parameter to a type which doesn't need it.
1312 Erroneous code example:
1314 ```compile_fail,E0110
1315 type X = u32<'static>; // error: lifetime parameters are not allowed on
1319 Please check that the correct type was used and recheck its definition; perhaps
1320 it doesn't need the lifetime parameter. Example:
1323 type X = u32; // ok!
1328 You can only define an inherent implementation for a type in the same crate
1329 where the type was defined. For example, an `impl` block as below is not allowed
1330 since `Vec` is defined in the standard library:
1332 ```compile_fail,E0116
1333 impl Vec<u8> { } // error
1336 To fix this problem, you can do either of these things:
1338 - define a trait that has the desired associated functions/types/constants and
1339 implement the trait for the type in question
1340 - define a new type wrapping the type and define an implementation on the new
1343 Note that using the `type` keyword does not work here because `type` only
1344 introduces a type alias:
1346 ```compile_fail,E0116
1347 type Bytes = Vec<u8>;
1349 impl Bytes { } // error, same as above
1354 This error indicates a violation of one of Rust's orphan rules for trait
1355 implementations. The rule prohibits any implementation of a foreign trait (a
1356 trait defined in another crate) where
1358 - the type that is implementing the trait is foreign
1359 - all of the parameters being passed to the trait (if there are any) are also
1362 Here's one example of this error:
1364 ```compile_fail,E0117
1365 impl Drop for u32 {}
1368 To avoid this kind of error, ensure that at least one local type is referenced
1372 pub struct Foo; // you define your type in your crate
1374 impl Drop for Foo { // and you can implement the trait on it!
1375 // code of trait implementation here
1376 # fn drop(&mut self) { }
1379 impl From<Foo> for i32 { // or you use a type from your crate as
1381 fn from(i: Foo) -> i32 {
1387 Alternatively, define a trait locally and implement that instead:
1391 fn get(&self) -> usize;
1395 fn get(&self) -> usize { 0 }
1399 For information on the design of the orphan rules, see [RFC 1023].
1401 [RFC 1023]: https://github.com/rust-lang/rfcs/blob/master/text/1023-rebalancing-coherence.md
1405 You're trying to write an inherent implementation for something which isn't a
1406 struct nor an enum. Erroneous code example:
1408 ```compile_fail,E0118
1409 impl (u8, u8) { // error: no base type found for inherent implementation
1410 fn get_state(&self) -> String {
1416 To fix this error, please implement a trait on the type or wrap it in a struct.
1420 // we create a trait here
1421 trait LiveLongAndProsper {
1422 fn get_state(&self) -> String;
1425 // and now you can implement it on (u8, u8)
1426 impl LiveLongAndProsper for (u8, u8) {
1427 fn get_state(&self) -> String {
1428 "He's dead, Jim!".to_owned()
1433 Alternatively, you can create a newtype. A newtype is a wrapping tuple-struct.
1434 For example, `NewType` is a newtype over `Foo` in `struct NewType(Foo)`.
1438 struct TypeWrapper((u8, u8));
1441 fn get_state(&self) -> String {
1442 "Fascinating!".to_owned()
1449 An attempt was made to implement Drop on a trait, which is not allowed: only
1450 structs and enums can implement Drop. An example causing this error:
1452 ```compile_fail,E0120
1455 impl Drop for MyTrait {
1456 fn drop(&mut self) {}
1460 A workaround for this problem is to wrap the trait up in a struct, and implement
1461 Drop on that. An example is shown below:
1465 struct MyWrapper<T: MyTrait> { foo: T }
1467 impl <T: MyTrait> Drop for MyWrapper<T> {
1468 fn drop(&mut self) {}
1473 Alternatively, wrapping trait objects requires something like the following:
1478 //or Box<MyTrait>, if you wanted an owned trait object
1479 struct MyWrapper<'a> { foo: &'a MyTrait }
1481 impl <'a> Drop for MyWrapper<'a> {
1482 fn drop(&mut self) {}
1488 In order to be consistent with Rust's lack of global type inference, type
1489 placeholders are disallowed by design in item signatures.
1491 Examples of this error include:
1493 ```compile_fail,E0121
1494 fn foo() -> _ { 5 } // error, explicitly write out the return type instead
1496 static BAR: _ = "test"; // error, explicitly write out the type instead
1501 You declared two fields of a struct with the same name. Erroneous code
1504 ```compile_fail,E0124
1507 field1: i32, // error: field is already declared
1511 Please verify that the field names have been correctly spelled. Example:
1522 It is not possible to define `main` with generic parameters.
1523 When `main` is present, it must take no arguments and return `()`.
1524 Erroneous code example:
1526 ```compile_fail,E0131
1527 fn main<T>() { // error: main function is not allowed to have generic parameters
1533 A function with the `start` attribute was declared with type parameters.
1535 Erroneous code example:
1537 ```compile_fail,E0132
1544 It is not possible to declare type parameters on a function that has the `start`
1545 attribute. Such a function must have the following type signature (for more
1546 information: http://doc.rust-lang.org/stable/book/first-edition/no-stdlib.html):
1550 fn(isize, *const *const u8) -> isize;
1559 fn my_start(argc: isize, argv: *const *const u8) -> isize {
1566 This error means that an attempt was made to match a struct type enum
1567 variant as a non-struct type:
1569 ```compile_fail,E0164
1570 enum Foo { B { i: u32 } }
1572 fn bar(foo: Foo) -> u32 {
1574 Foo::B(i) => i, // error E0164
1579 Try using `{}` instead:
1582 enum Foo { B { i: u32 } }
1584 fn bar(foo: Foo) -> u32 {
1593 Explicitly implementing both Drop and Copy for a type is currently disallowed.
1594 This feature can make some sense in theory, but the current implementation is
1595 incorrect and can lead to memory unsafety (see [issue #20126][iss20126]), so
1596 it has been disabled for now.
1598 [iss20126]: https://github.com/rust-lang/rust/issues/20126
1602 An associated function for a trait was defined to be static, but an
1603 implementation of the trait declared the same function to be a method (i.e., to
1604 take a `self` parameter).
1606 Here's an example of this error:
1608 ```compile_fail,E0185
1616 // error, method `foo` has a `&self` declaration in the impl, but not in
1624 An associated function for a trait was defined to be a method (i.e., to take a
1625 `self` parameter), but an implementation of the trait declared the same function
1628 Here's an example of this error:
1630 ```compile_fail,E0186
1638 // error, method `foo` has a `&self` declaration in the trait, but not in
1646 Trait objects need to have all associated types specified. Erroneous code
1649 ```compile_fail,E0191
1654 type Foo = Trait; // error: the value of the associated type `Bar` (from
1655 // the trait `Trait`) must be specified
1658 Please verify you specified all associated types of the trait and that you
1659 used the right trait. Example:
1666 type Foo = Trait<Bar=i32>; // ok!
1671 Negative impls are only allowed for auto traits. For more
1672 information see the [opt-in builtin traits RFC][RFC 19].
1674 [RFC 19]: https://github.com/rust-lang/rfcs/blob/master/text/0019-opt-in-builtin-traits.md
1678 #### Note: this error code is no longer emitted by the compiler.
1680 `where` clauses must use generic type parameters: it does not make sense to use
1681 them otherwise. An example causing this error:
1688 #[derive(Copy,Clone)]
1693 impl Foo for Wrapper<u32> where Wrapper<u32>: Clone {
1698 This use of a `where` clause is strange - a more common usage would look
1699 something like the following:
1706 #[derive(Copy,Clone)]
1710 impl <T> Foo for Wrapper<T> where Wrapper<T>: Clone {
1715 Here, we're saying that the implementation exists on Wrapper only when the
1716 wrapped type `T` implements `Clone`. The `where` clause is important because
1717 some types will not implement `Clone`, and thus will not get this method.
1719 In our erroneous example, however, we're referencing a single concrete type.
1720 Since we know for certain that `Wrapper<u32>` implements `Clone`, there's no
1721 reason to also specify it in a `where` clause.
1725 A type parameter was declared which shadows an existing one. An example of this
1728 ```compile_fail,E0194
1730 fn do_something(&self) -> T;
1731 fn do_something_else<T: Clone>(&self, bar: T);
1735 In this example, the trait `Foo` and the trait method `do_something_else` both
1736 define a type parameter `T`. This is not allowed: if the method wishes to
1737 define a type parameter, it must use a different name for it.
1741 Your method's lifetime parameters do not match the trait declaration.
1742 Erroneous code example:
1744 ```compile_fail,E0195
1746 fn bar<'a,'b:'a>(x: &'a str, y: &'b str);
1751 impl Trait for Foo {
1752 fn bar<'a,'b>(x: &'a str, y: &'b str) {
1753 // error: lifetime parameters or bounds on method `bar`
1754 // do not match the trait declaration
1759 The lifetime constraint `'b` for bar() implementation does not match the
1760 trait declaration. Ensure lifetime declarations match exactly in both trait
1761 declaration and implementation. Example:
1765 fn t<'a,'b:'a>(x: &'a str, y: &'b str);
1770 impl Trait for Foo {
1771 fn t<'a,'b:'a>(x: &'a str, y: &'b str) { // ok!
1778 Safe traits should not have unsafe implementations, therefore marking an
1779 implementation for a safe trait unsafe will cause a compiler error. Removing
1780 the unsafe marker on the trait noted in the error will resolve this problem.
1782 ```compile_fail,E0199
1787 // this won't compile because Bar is safe
1788 unsafe impl Bar for Foo { }
1789 // this will compile
1790 impl Bar for Foo { }
1795 Unsafe traits must have unsafe implementations. This error occurs when an
1796 implementation for an unsafe trait isn't marked as unsafe. This may be resolved
1797 by marking the unsafe implementation as unsafe.
1799 ```compile_fail,E0200
1802 unsafe trait Bar { }
1804 // this won't compile because Bar is unsafe and impl isn't unsafe
1805 impl Bar for Foo { }
1806 // this will compile
1807 unsafe impl Bar for Foo { }
1812 It is an error to define two associated items (like methods, associated types,
1813 associated functions, etc.) with the same identifier.
1817 ```compile_fail,E0201
1821 fn bar(&self) -> bool { self.0 > 5 }
1822 fn bar() {} // error: duplicate associated function
1827 fn baz(&self) -> bool;
1833 fn baz(&self) -> bool { true }
1835 // error: duplicate method
1836 fn baz(&self) -> bool { self.0 > 5 }
1838 // error: duplicate associated type
1843 Note, however, that items with the same name are allowed for inherent `impl`
1844 blocks that don't overlap:
1850 fn bar(&self) -> bool { self.0 > 5 }
1854 fn bar(&self) -> bool { self.0 }
1860 Inherent associated types were part of [RFC 195] but are not yet implemented.
1861 See [the tracking issue][iss8995] for the status of this implementation.
1863 [RFC 195]: https://github.com/rust-lang/rfcs/blob/master/text/0195-associated-items.md
1864 [iss8995]: https://github.com/rust-lang/rust/issues/8995
1868 An attempt to implement the `Copy` trait for a struct failed because one of the
1869 fields does not implement `Copy`. To fix this, you must implement `Copy` for the
1870 mentioned field. Note that this may not be possible, as in the example of
1872 ```compile_fail,E0204
1877 impl Copy for Foo { }
1880 This fails because `Vec<T>` does not implement `Copy` for any `T`.
1882 Here's another example that will fail:
1884 ```compile_fail,E0204
1891 This fails because `&mut T` is not `Copy`, even when `T` is `Copy` (this
1892 differs from the behavior for `&T`, which is always `Copy`).
1897 An attempt to implement the `Copy` trait for an enum failed because one of the
1898 variants does not implement `Copy`. To fix this, you must implement `Copy` for
1899 the mentioned variant. Note that this may not be possible, as in the example of
1901 ```compile_fail,E0205
1907 impl Copy for Foo { }
1910 This fails because `Vec<T>` does not implement `Copy` for any `T`.
1912 Here's another example that will fail:
1914 ```compile_fail,E0205
1922 This fails because `&mut T` is not `Copy`, even when `T` is `Copy` (this
1923 differs from the behavior for `&T`, which is always `Copy`).
1928 You can only implement `Copy` for a struct or enum. Both of the following
1929 examples will fail, because neither `[u8; 256]` nor `&'static mut Bar`
1930 (mutable reference to `Bar`) is a struct or enum:
1932 ```compile_fail,E0206
1933 type Foo = [u8; 256];
1934 impl Copy for Foo { } // error
1936 #[derive(Copy, Clone)]
1938 impl Copy for &'static mut Bar { } // error
1943 Any type parameter or lifetime parameter of an `impl` must meet at least one of
1944 the following criteria:
1946 - it appears in the self type of the impl
1947 - for a trait impl, it appears in the trait reference
1948 - it is bound as an associated type
1952 Suppose we have a struct `Foo` and we would like to define some methods for it.
1953 The following definition leads to a compiler error:
1955 ```compile_fail,E0207
1958 impl<T: Default> Foo {
1959 // error: the type parameter `T` is not constrained by the impl trait, self
1960 // type, or predicates [E0207]
1961 fn get(&self) -> T {
1962 <T as Default>::default()
1967 The problem is that the parameter `T` does not appear in the self type (`Foo`)
1968 of the impl. In this case, we can fix the error by moving the type parameter
1969 from the `impl` to the method `get`:
1975 // Move the type parameter from the impl to the method
1977 fn get<T: Default>(&self) -> T {
1978 <T as Default>::default()
1985 As another example, suppose we have a `Maker` trait and want to establish a
1986 type `FooMaker` that makes `Foo`s:
1988 ```compile_fail,E0207
1991 fn make(&mut self) -> Self::Item;
2000 impl<T: Default> Maker for FooMaker {
2001 // error: the type parameter `T` is not constrained by the impl trait, self
2002 // type, or predicates [E0207]
2005 fn make(&mut self) -> Foo<T> {
2006 Foo { foo: <T as Default>::default() }
2011 This fails to compile because `T` does not appear in the trait or in the
2014 One way to work around this is to introduce a phantom type parameter into
2015 `FooMaker`, like so:
2018 use std::marker::PhantomData;
2022 fn make(&mut self) -> Self::Item;
2029 // Add a type parameter to `FooMaker`
2030 struct FooMaker<T> {
2031 phantom: PhantomData<T>,
2034 impl<T: Default> Maker for FooMaker<T> {
2037 fn make(&mut self) -> Foo<T> {
2039 foo: <T as Default>::default(),
2045 Another way is to do away with the associated type in `Maker` and use an input
2046 type parameter instead:
2049 // Use a type parameter instead of an associated type here
2051 fn make(&mut self) -> Item;
2060 impl<T: Default> Maker<Foo<T>> for FooMaker {
2061 fn make(&mut self) -> Foo<T> {
2062 Foo { foo: <T as Default>::default() }
2067 ### Additional information
2069 For more information, please see [RFC 447].
2071 [RFC 447]: https://github.com/rust-lang/rfcs/blob/master/text/0447-no-unused-impl-parameters.md
2075 This error indicates a violation of one of Rust's orphan rules for trait
2076 implementations. The rule concerns the use of type parameters in an
2077 implementation of a foreign trait (a trait defined in another crate), and
2078 states that type parameters must be "covered" by a local type. To understand
2079 what this means, it is perhaps easiest to consider a few examples.
2081 If `ForeignTrait` is a trait defined in some external crate `foo`, then the
2082 following trait `impl` is an error:
2084 ```compile_fail,E0210
2085 # #[cfg(for_demonstration_only)]
2087 # #[cfg(for_demonstration_only)]
2088 use foo::ForeignTrait;
2089 # use std::panic::UnwindSafe as ForeignTrait;
2091 impl<T> ForeignTrait for T { } // error
2095 To work around this, it can be covered with a local type, `MyType`:
2098 # use std::panic::UnwindSafe as ForeignTrait;
2099 struct MyType<T>(T);
2100 impl<T> ForeignTrait for MyType<T> { } // Ok
2103 Please note that a type alias is not sufficient.
2105 For another example of an error, suppose there's another trait defined in `foo`
2106 named `ForeignTrait2` that takes two type parameters. Then this `impl` results
2107 in the same rule violation:
2109 ```ignore (cannot-doctest-multicrate-project)
2111 impl<T> ForeignTrait2<T, MyType<T>> for MyType2 { } // error
2114 The reason for this is that there are two appearances of type parameter `T` in
2115 the `impl` header, both as parameters for `ForeignTrait2`. The first appearance
2116 is uncovered, and so runs afoul of the orphan rule.
2118 Consider one more example:
2120 ```ignore (cannot-doctest-multicrate-project)
2121 impl<T> ForeignTrait2<MyType<T>, T> for MyType2 { } // Ok
2124 This only differs from the previous `impl` in that the parameters `T` and
2125 `MyType<T>` for `ForeignTrait2` have been swapped. This example does *not*
2126 violate the orphan rule; it is permitted.
2128 To see why that last example was allowed, you need to understand the general
2129 rule. Unfortunately this rule is a bit tricky to state. Consider an `impl`:
2131 ```ignore (only-for-syntax-highlight)
2132 impl<P1, ..., Pm> ForeignTrait<T1, ..., Tn> for T0 { ... }
2135 where `P1, ..., Pm` are the type parameters of the `impl` and `T0, ..., Tn`
2136 are types. One of the types `T0, ..., Tn` must be a local type (this is another
2137 orphan rule, see the explanation for E0117). Let `i` be the smallest integer
2138 such that `Ti` is a local type. Then no type parameter can appear in any of the
2141 For information on the design of the orphan rules, see [RFC 1023].
2143 [RFC 1023]: https://github.com/rust-lang/rfcs/blob/master/text/1023-rebalancing-coherence.md
2148 You used a function or type which doesn't fit the requirements for where it was
2149 used. Erroneous code examples:
2152 #![feature(intrinsics)]
2154 extern "rust-intrinsic" {
2155 fn size_of<T>(); // error: intrinsic has wrong type
2160 fn main() -> i32 { 0 }
2161 // error: main function expects type: `fn() {main}`: expected (), found i32
2168 // error: mismatched types in range: expected u8, found i8
2178 fn x(self: Rc<Foo>) {}
2179 // error: mismatched self type: expected `Foo`: expected struct
2180 // `Foo`, found struct `alloc::rc::Rc`
2184 For the first code example, please check the function definition. Example:
2187 #![feature(intrinsics)]
2189 extern "rust-intrinsic" {
2190 fn size_of<T>() -> usize; // ok!
2194 The second case example is a bit particular : the main function must always
2195 have this definition:
2201 They never take parameters and never return types.
2203 For the third example, when you match, all patterns must have the same type
2204 as the type you're matching on. Example:
2210 0u8..=3u8 => (), // ok!
2215 And finally, for the last example, only `Box<Self>`, `&Self`, `Self`,
2216 or `&mut Self` work as explicit self parameters. Example:
2222 fn x(self: Box<Foo>) {} // ok!
2229 You used an associated type which isn't defined in the trait.
2230 Erroneous code example:
2232 ```compile_fail,E0220
2237 type Foo = T1<F=i32>; // error: associated type `F` not found for `T1`
2244 // error: Baz is used but not declared
2245 fn return_bool(&self, _: &Self::Bar, _: &Self::Baz) -> bool;
2249 Make sure that you have defined the associated type in the trait body.
2250 Also, verify that you used the right trait or you didn't misspell the
2251 associated type name. Example:
2258 type Foo = T1<Bar=i32>; // ok!
2264 type Baz; // we declare `Baz` in our trait.
2266 // and now we can use it here:
2267 fn return_bool(&self, _: &Self::Bar, _: &Self::Baz) -> bool;
2273 An attempt was made to retrieve an associated type, but the type was ambiguous.
2276 ```compile_fail,E0221
2292 In this example, `Foo` defines an associated type `A`. `Bar` inherits that type
2293 from `Foo`, and defines another associated type of the same name. As a result,
2294 when we attempt to use `Self::A`, it's ambiguous whether we mean the `A` defined
2295 by `Foo` or the one defined by `Bar`.
2297 There are two options to work around this issue. The first is simply to rename
2298 one of the types. Alternatively, one can specify the intended type using the
2312 let _: <Self as Bar>::A;
2319 An attempt was made to retrieve an associated type, but the type was ambiguous.
2322 ```compile_fail,E0223
2323 trait MyTrait {type X; }
2326 let foo: MyTrait::X;
2330 The problem here is that we're attempting to take the type of X from MyTrait.
2331 Unfortunately, the type of X is not defined, because it's only made concrete in
2332 implementations of the trait. A working version of this code might look like:
2335 trait MyTrait {type X; }
2338 impl MyTrait for MyStruct {
2343 let foo: <MyStruct as MyTrait>::X;
2347 This syntax specifies that we want the X type from MyTrait, as made concrete in
2348 MyStruct. The reason that we cannot simply use `MyStruct::X` is that MyStruct
2349 might implement two different traits with identically-named associated types.
2350 This syntax allows disambiguation between the two.
2354 You attempted to use multiple types as bounds for a closure or trait object.
2355 Rust does not currently support this. A simple example that causes this error:
2357 ```compile_fail,E0225
2359 let _: Box<dyn std::io::Read + std::io::Write>;
2363 Auto traits such as Send and Sync are an exception to this rule:
2364 It's possible to have bounds of one non-builtin trait, plus any number of
2365 auto traits. For example, the following compiles correctly:
2369 let _: Box<dyn std::io::Read + Send + Sync>;
2375 An associated type binding was done outside of the type parameter declaration
2376 and `where` clause. Erroneous code example:
2378 ```compile_fail,E0229
2381 fn boo(&self) -> <Self as Foo>::A;
2386 impl Foo for isize {
2388 fn boo(&self) -> usize { 42 }
2391 fn baz<I>(x: &<I as Foo<A=Bar>>::A) {}
2392 // error: associated type bindings are not allowed here
2395 To solve this error, please move the type bindings in the type parameter
2400 # trait Foo { type A; }
2401 fn baz<I: Foo<A=Bar>>(x: &<I as Foo>::A) {} // ok!
2404 Or in the `where` clause:
2408 # trait Foo { type A; }
2409 fn baz<I>(x: &<I as Foo>::A) where I: Foo<A=Bar> {}
2414 #### Note: this error code is no longer emitted by the compiler.
2416 This error indicates that not enough type parameters were found in a type or
2419 For example, the `Foo` struct below is defined to be generic in `T`, but the
2420 type parameter is missing in the definition of `Bar`:
2422 ```compile_fail,E0107
2423 struct Foo<T> { x: T }
2425 struct Bar { x: Foo }
2430 #### Note: this error code is no longer emitted by the compiler.
2432 This error indicates that too many type parameters were found in a type or
2435 For example, the `Foo` struct below has no type parameters, but is supplied
2436 with two in the definition of `Bar`:
2438 ```compile_fail,E0107
2439 struct Foo { x: bool }
2441 struct Bar<S, T> { x: Foo<S, T> }
2446 A cross-crate opt-out trait was implemented on something which wasn't a struct
2447 or enum type. Erroneous code example:
2449 ```compile_fail,E0321
2450 #![feature(optin_builtin_traits)]
2454 impl !Sync for Foo {}
2456 unsafe impl Send for &'static Foo {}
2457 // error: cross-crate traits with a default impl, like `core::marker::Send`,
2458 // can only be implemented for a struct/enum type, not
2462 Only structs and enums are permitted to impl Send, Sync, and other opt-out
2463 trait, and the struct or enum must be local to the current crate. So, for
2464 example, `unsafe impl Send for Rc<Foo>` is not allowed.
2468 The `Sized` trait is a special trait built-in to the compiler for types with a
2469 constant size known at compile-time. This trait is automatically implemented
2470 for types as needed by the compiler, and it is currently disallowed to
2471 explicitly implement it for a type.
2475 An associated const was implemented when another trait item was expected.
2476 Erroneous code example:
2478 ```compile_fail,E0323
2487 // error: item `N` is an associated const, which doesn't match its
2488 // trait `<Bar as Foo>`
2492 Please verify that the associated const wasn't misspelled and the correct trait
2493 was implemented. Example:
2503 type N = u32; // ok!
2517 const N : u32 = 0; // ok!
2523 A method was implemented when another trait item was expected. Erroneous
2526 ```compile_fail,E0324
2537 // error: item `N` is an associated method, which doesn't match its
2538 // trait `<Bar as Foo>`
2542 To fix this error, please verify that the method name wasn't misspelled and
2543 verify that you are indeed implementing the correct trait items. Example:
2563 An associated type was implemented when another trait item was expected.
2564 Erroneous code example:
2566 ```compile_fail,E0325
2575 // error: item `N` is an associated type, which doesn't match its
2576 // trait `<Bar as Foo>`
2580 Please verify that the associated type name wasn't misspelled and your
2581 implementation corresponds to the trait definition. Example:
2591 type N = u32; // ok!
2605 const N : u32 = 0; // ok!
2611 The types of any associated constants in a trait implementation must match the
2612 types in the trait definition. This error indicates that there was a mismatch.
2614 Here's an example of this error:
2616 ```compile_fail,E0326
2624 const BAR: u32 = 5; // error, expected bool, found u32
2630 The Unsize trait should not be implemented directly. All implementations of
2631 Unsize are provided automatically by the compiler.
2633 Erroneous code example:
2635 ```compile_fail,E0328
2638 use std::marker::Unsize;
2642 impl<T> Unsize<T> for MyType {}
2645 If you are defining your own smart pointer type and would like to enable
2646 conversion from a sized to an unsized type with the
2647 [DST coercion system][RFC 982], use [`CoerceUnsized`] instead.
2650 #![feature(coerce_unsized)]
2652 use std::ops::CoerceUnsized;
2654 pub struct MyType<T: ?Sized> {
2655 field_with_unsized_type: T,
2658 impl<T, U> CoerceUnsized<MyType<U>> for MyType<T>
2659 where T: CoerceUnsized<U> {}
2662 [RFC 982]: https://github.com/rust-lang/rfcs/blob/master/text/0982-dst-coercion.md
2663 [`CoerceUnsized`]: https://doc.rust-lang.org/std/ops/trait.CoerceUnsized.html
2667 // Associated consts can now be accessed through generic type parameters, and
2668 // this error is no longer emitted.
2670 // FIXME: consider whether to leave it in the error index, or remove it entirely
2671 // as associated consts is not stabilized yet.
2674 An attempt was made to access an associated constant through either a generic
2675 type parameter or `Self`. This is not supported yet. An example causing this
2676 error is shown below:
2685 impl Foo for MyStruct {
2686 const BAR: f64 = 0f64;
2689 fn get_bar_bad<F: Foo>(t: F) -> f64 {
2694 Currently, the value of `BAR` for a particular type can only be accessed
2695 through a concrete type, as shown below:
2704 fn get_bar_good() -> f64 {
2705 <MyStruct as Foo>::BAR
2712 An attempt was made to implement `Drop` on a concrete specialization of a
2713 generic type. An example is shown below:
2715 ```compile_fail,E0366
2720 impl Drop for Foo<u32> {
2721 fn drop(&mut self) {}
2725 This code is not legal: it is not possible to specialize `Drop` to a subset of
2726 implementations of a generic type. One workaround for this is to wrap the
2727 generic type, as shown below:
2739 fn drop(&mut self) {}
2745 An attempt was made to implement `Drop` on a specialization of a generic type.
2746 An example is shown below:
2748 ```compile_fail,E0367
2751 struct MyStruct<T> {
2755 impl<T: Foo> Drop for MyStruct<T> {
2756 fn drop(&mut self) {}
2760 This code is not legal: it is not possible to specialize `Drop` to a subset of
2761 implementations of a generic type. In order for this code to work, `MyStruct`
2762 must also require that `T` implements `Foo`. Alternatively, another option is
2763 to wrap the generic type in another that specializes appropriately:
2768 struct MyStruct<T> {
2772 struct MyStructWrapper<T: Foo> {
2776 impl <T: Foo> Drop for MyStructWrapper<T> {
2777 fn drop(&mut self) {}
2783 This error indicates that a binary assignment operator like `+=` or `^=` was
2784 applied to a type that doesn't support it. For example:
2786 ```compile_fail,E0368
2787 let mut x = 12f32; // error: binary operation `<<` cannot be applied to
2793 To fix this error, please check that this type implements this binary
2797 let mut x = 12u32; // the `u32` type does implement the `ShlAssign` trait
2802 It is also possible to overload most operators for your own type by
2803 implementing the `[OP]Assign` traits from `std::ops`.
2805 Another problem you might be facing is this: suppose you've overloaded the `+`
2806 operator for some type `Foo` by implementing the `std::ops::Add` trait for
2807 `Foo`, but you find that using `+=` does not work, as in this example:
2809 ```compile_fail,E0368
2817 fn add(self, rhs: Foo) -> Foo {
2823 let mut x: Foo = Foo(5);
2824 x += Foo(7); // error, `+= cannot be applied to the type `Foo`
2828 This is because `AddAssign` is not automatically implemented, so you need to
2829 manually implement it for your type.
2833 A binary operation was attempted on a type which doesn't support it.
2834 Erroneous code example:
2836 ```compile_fail,E0369
2837 let x = 12f32; // error: binary operation `<<` cannot be applied to
2843 To fix this error, please check that this type implements this binary
2847 let x = 12u32; // the `u32` type does implement it:
2848 // https://doc.rust-lang.org/stable/std/ops/trait.Shl.html
2853 It is also possible to overload most operators for your own type by
2854 implementing traits from `std::ops`.
2856 String concatenation appends the string on the right to the string on the
2857 left and may require reallocation. This requires ownership of the string
2858 on the left. If something should be added to a string literal, move the
2859 literal to the heap by allocating it with `to_owned()` like in
2860 `"Your text".to_owned()`.
2865 The maximum value of an enum was reached, so it cannot be automatically
2866 set in the next enum value. Erroneous code example:
2869 #[deny(overflowing_literals)]
2871 X = 0x7fffffffffffffff,
2872 Y, // error: enum discriminant overflowed on value after
2873 // 9223372036854775807: i64; set explicitly via
2874 // Y = -9223372036854775808 if that is desired outcome
2878 To fix this, please set manually the next enum value or put the enum variant
2879 with the maximum value at the end of the enum. Examples:
2883 X = 0x7fffffffffffffff,
2893 X = 0x7fffffffffffffff,
2899 When `Trait2` is a subtrait of `Trait1` (for example, when `Trait2` has a
2900 definition like `trait Trait2: Trait1 { ... }`), it is not allowed to implement
2901 `Trait1` for `Trait2`. This is because `Trait2` already implements `Trait1` by
2902 definition, so it is not useful to do this.
2906 ```compile_fail,E0371
2907 trait Foo { fn foo(&self) { } }
2911 impl Bar for Baz { } // error, `Baz` implements `Bar` by definition
2912 impl Foo for Baz { } // error, `Baz` implements `Bar` which implements `Foo`
2913 impl Baz for Baz { } // error, `Baz` (trivially) implements `Baz`
2914 impl Baz for Bar { } // Note: This is OK
2919 A struct without a field containing an unsized type cannot implement
2921 [unsized type](https://doc.rust-lang.org/book/first-edition/unsized-types.html)
2922 is any type that the compiler doesn't know the length or alignment of at
2923 compile time. Any struct containing an unsized type is also unsized.
2925 Example of erroneous code:
2927 ```compile_fail,E0374
2928 #![feature(coerce_unsized)]
2929 use std::ops::CoerceUnsized;
2931 struct Foo<T: ?Sized> {
2935 // error: Struct `Foo` has no unsized fields that need `CoerceUnsized`.
2936 impl<T, U> CoerceUnsized<Foo<U>> for Foo<T>
2937 where T: CoerceUnsized<U> {}
2940 `CoerceUnsized` is used to coerce one struct containing an unsized type
2941 into another struct containing a different unsized type. If the struct
2942 doesn't have any fields of unsized types then you don't need explicit
2943 coercion to get the types you want. To fix this you can either
2944 not try to implement `CoerceUnsized` or you can add a field that is
2945 unsized to the struct.
2950 #![feature(coerce_unsized)]
2951 use std::ops::CoerceUnsized;
2953 // We don't need to impl `CoerceUnsized` here.
2958 // We add the unsized type field to the struct.
2959 struct Bar<T: ?Sized> {
2964 // The struct has an unsized field so we can implement
2965 // `CoerceUnsized` for it.
2966 impl<T, U> CoerceUnsized<Bar<U>> for Bar<T>
2967 where T: CoerceUnsized<U> {}
2970 Note that `CoerceUnsized` is mainly used by smart pointers like `Box`, `Rc`
2971 and `Arc` to be able to mark that they can coerce unsized types that they
2976 A struct with more than one field containing an unsized type cannot implement
2977 `CoerceUnsized`. This only occurs when you are trying to coerce one of the
2978 types in your struct to another type in the struct. In this case we try to
2979 impl `CoerceUnsized` from `T` to `U` which are both types that the struct
2980 takes. An [unsized type] is any type that the compiler doesn't know the length
2981 or alignment of at compile time. Any struct containing an unsized type is also
2984 Example of erroneous code:
2986 ```compile_fail,E0375
2987 #![feature(coerce_unsized)]
2988 use std::ops::CoerceUnsized;
2990 struct Foo<T: ?Sized, U: ?Sized> {
2996 // error: Struct `Foo` has more than one unsized field.
2997 impl<T, U> CoerceUnsized<Foo<U, T>> for Foo<T, U> {}
3000 `CoerceUnsized` only allows for coercion from a structure with a single
3001 unsized type field to another struct with a single unsized type field.
3002 In fact Rust only allows for a struct to have one unsized type in a struct
3003 and that unsized type must be the last field in the struct. So having two
3004 unsized types in a single struct is not allowed by the compiler. To fix this
3005 use only one field containing an unsized type in the struct and then use
3006 multiple structs to manage each unsized type field you need.
3011 #![feature(coerce_unsized)]
3012 use std::ops::CoerceUnsized;
3014 struct Foo<T: ?Sized> {
3019 impl <T, U> CoerceUnsized<Foo<U>> for Foo<T>
3020 where T: CoerceUnsized<U> {}
3022 fn coerce_foo<T: CoerceUnsized<U>, U>(t: T) -> Foo<U> {
3023 Foo { a: 12i32, b: t } // we use coercion to get the `Foo<U>` type we need
3027 [unsized type]: https://doc.rust-lang.org/book/first-edition/unsized-types.html
3031 The type you are trying to impl `CoerceUnsized` for is not a struct.
3032 `CoerceUnsized` can only be implemented for a struct. Unsized types are
3033 already able to be coerced without an implementation of `CoerceUnsized`
3034 whereas a struct containing an unsized type needs to know the unsized type
3035 field it's containing is able to be coerced. An
3036 [unsized type](https://doc.rust-lang.org/book/first-edition/unsized-types.html)
3037 is any type that the compiler doesn't know the length or alignment of at
3038 compile time. Any struct containing an unsized type is also unsized.
3040 Example of erroneous code:
3042 ```compile_fail,E0376
3043 #![feature(coerce_unsized)]
3044 use std::ops::CoerceUnsized;
3046 struct Foo<T: ?Sized> {
3050 // error: The type `U` is not a struct
3051 impl<T, U> CoerceUnsized<U> for Foo<T> {}
3054 The `CoerceUnsized` trait takes a struct type. Make sure the type you are
3055 providing to `CoerceUnsized` is a struct with only the last field containing an
3061 #![feature(coerce_unsized)]
3062 use std::ops::CoerceUnsized;
3068 // The `Foo<U>` is a struct so `CoerceUnsized` can be implemented
3069 impl<T, U> CoerceUnsized<Foo<U>> for Foo<T> where T: CoerceUnsized<U> {}
3072 Note that in Rust, structs can only contain an unsized type if the field
3073 containing the unsized type is the last and only unsized type field in the
3078 The `DispatchFromDyn` trait currently can only be implemented for
3079 builtin pointer types and structs that are newtype wrappers around them
3080 — that is, the struct must have only one field (except for`PhantomData`),
3081 and that field must itself implement `DispatchFromDyn`.
3086 #![feature(dispatch_from_dyn, unsize)]
3089 ops::DispatchFromDyn,
3092 struct Ptr<T: ?Sized>(*const T);
3094 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Ptr<U>> for Ptr<T>
3101 #![feature(dispatch_from_dyn)]
3103 ops::DispatchFromDyn,
3104 marker::PhantomData,
3109 _phantom: PhantomData<()>,
3112 impl<T, U> DispatchFromDyn<Wrapper<U>> for Wrapper<T>
3114 T: DispatchFromDyn<U>,
3118 Example of illegal `DispatchFromDyn` implementation
3119 (illegal because of extra field)
3121 ```compile-fail,E0378
3122 #![feature(dispatch_from_dyn)]
3123 use std::ops::DispatchFromDyn;
3125 struct WrapperExtraField<T> {
3130 impl<T, U> DispatchFromDyn<WrapperExtraField<U>> for WrapperExtraField<T>
3132 T: DispatchFromDyn<U>,
3138 You tried to implement methods for a primitive type. Erroneous code example:
3140 ```compile_fail,E0390
3146 // error: only a single inherent implementation marked with
3147 // `#[lang = "mut_ptr"]` is allowed for the `*mut T` primitive
3150 This isn't allowed, but using a trait to implement a method is a good solution.
3162 impl Bar for *mut Foo {
3169 This error indicates that a type or lifetime parameter has been declared
3170 but not actually used. Here is an example that demonstrates the error:
3172 ```compile_fail,E0392
3178 If the type parameter was included by mistake, this error can be fixed
3179 by simply removing the type parameter, as shown below:
3187 Alternatively, if the type parameter was intentionally inserted, it must be
3188 used. A simple fix is shown below:
3196 This error may also commonly be found when working with unsafe code. For
3197 example, when using raw pointers one may wish to specify the lifetime for
3198 which the pointed-at data is valid. An initial attempt (below) causes this
3201 ```compile_fail,E0392
3207 We want to express the constraint that Foo should not outlive `'a`, because
3208 the data pointed to by `T` is only valid for that lifetime. The problem is
3209 that there are no actual uses of `'a`. It's possible to work around this
3210 by adding a PhantomData type to the struct, using it to tell the compiler
3211 to act as if the struct contained a borrowed reference `&'a T`:
3214 use std::marker::PhantomData;
3216 struct Foo<'a, T: 'a> {
3218 phantom: PhantomData<&'a T>
3222 [PhantomData] can also be used to express information about unused type
3225 [PhantomData]: https://doc.rust-lang.org/std/marker/struct.PhantomData.html
3229 A type parameter which references `Self` in its default value was not specified.
3230 Example of erroneous code:
3232 ```compile_fail,E0393
3235 fn together_we_will_rule_the_galaxy(son: &A) {}
3236 // error: the type parameter `T` must be explicitly specified in an
3237 // object type because its default value `Self` references the
3241 A trait object is defined over a single, fully-defined trait. With a regular
3242 default parameter, this parameter can just be substituted in. However, if the
3243 default parameter is `Self`, the trait changes for each concrete type; i.e.
3244 `i32` will be expected to implement `A<i32>`, `bool` will be expected to
3245 implement `A<bool>`, etc... These types will not share an implementation of a
3246 fully-defined trait; instead they share implementations of a trait with
3247 different parameters substituted in for each implementation. This is
3248 irreconcilable with what we need to make a trait object work, and is thus
3249 disallowed. Making the trait concrete by explicitly specifying the value of the
3250 defaulted parameter will fix this issue. Fixed example:
3255 fn together_we_will_rule_the_galaxy(son: &A<i32>) {} // Ok!
3260 You implemented a trait, overriding one or more of its associated types but did
3261 not reimplement its default methods.
3263 Example of erroneous code:
3265 ```compile_fail,E0399
3266 #![feature(associated_type_defaults)]
3274 // error - the following trait items need to be reimplemented as
3275 // `Assoc` was overridden: `bar`
3280 To fix this, add an implementation for each default method from the trait:
3283 #![feature(associated_type_defaults)]
3292 fn bar(&self) {} // ok!
3298 The functional record update syntax is only allowed for structs. (Struct-like
3299 enum variants don't qualify, for example.)
3301 Erroneous code example:
3303 ```compile_fail,E0436
3304 enum PublicationFrequency {
3306 SemiMonthly { days: (u8, u8), annual_special: bool },
3309 fn one_up_competitor(competitor_frequency: PublicationFrequency)
3310 -> PublicationFrequency {
3311 match competitor_frequency {
3312 PublicationFrequency::Weekly => PublicationFrequency::SemiMonthly {
3313 days: (1, 15), annual_special: false
3315 c @ PublicationFrequency::SemiMonthly{ .. } =>
3316 PublicationFrequency::SemiMonthly {
3317 annual_special: true, ..c // error: functional record update
3318 // syntax requires a struct
3324 Rewrite the expression without functional record update syntax:
3327 enum PublicationFrequency {
3329 SemiMonthly { days: (u8, u8), annual_special: bool },
3332 fn one_up_competitor(competitor_frequency: PublicationFrequency)
3333 -> PublicationFrequency {
3334 match competitor_frequency {
3335 PublicationFrequency::Weekly => PublicationFrequency::SemiMonthly {
3336 days: (1, 15), annual_special: false
3338 PublicationFrequency::SemiMonthly{ days, .. } =>
3339 PublicationFrequency::SemiMonthly {
3340 days, annual_special: true // ok!
3348 The length of the platform-intrinsic function `simd_shuffle`
3349 wasn't specified. Erroneous code example:
3351 ```compile_fail,E0439
3352 #![feature(platform_intrinsics)]
3354 extern "platform-intrinsic" {
3355 fn simd_shuffle<A,B>(a: A, b: A, c: [u32; 8]) -> B;
3356 // error: invalid `simd_shuffle`, needs length: `simd_shuffle`
3360 The `simd_shuffle` function needs the length of the array passed as
3361 last parameter in its name. Example:
3364 #![feature(platform_intrinsics)]
3366 extern "platform-intrinsic" {
3367 fn simd_shuffle8<A,B>(a: A, b: A, c: [u32; 8]) -> B;
3373 A platform-specific intrinsic function has the wrong number of type
3374 parameters. Erroneous code example:
3376 ```compile_fail,E0440
3377 #![feature(repr_simd)]
3378 #![feature(platform_intrinsics)]
3381 struct f64x2(f64, f64);
3383 extern "platform-intrinsic" {
3384 fn x86_mm_movemask_pd<T>(x: f64x2) -> i32;
3385 // error: platform-specific intrinsic has wrong number of type
3390 Please refer to the function declaration to see if it corresponds
3391 with yours. Example:
3394 #![feature(repr_simd)]
3395 #![feature(platform_intrinsics)]
3398 struct f64x2(f64, f64);
3400 extern "platform-intrinsic" {
3401 fn x86_mm_movemask_pd(x: f64x2) -> i32;
3407 An unknown platform-specific intrinsic function was used. Erroneous
3410 ```compile_fail,E0441
3411 #![feature(repr_simd)]
3412 #![feature(platform_intrinsics)]
3415 struct i16x8(i16, i16, i16, i16, i16, i16, i16, i16);
3417 extern "platform-intrinsic" {
3418 fn x86_mm_adds_ep16(x: i16x8, y: i16x8) -> i16x8;
3419 // error: unrecognized platform-specific intrinsic function
3423 Please verify that the function name wasn't misspelled, and ensure
3424 that it is declared in the rust source code (in the file
3425 src/librustc_platform_intrinsics/x86.rs). Example:
3428 #![feature(repr_simd)]
3429 #![feature(platform_intrinsics)]
3432 struct i16x8(i16, i16, i16, i16, i16, i16, i16, i16);
3434 extern "platform-intrinsic" {
3435 fn x86_mm_adds_epi16(x: i16x8, y: i16x8) -> i16x8; // ok!
3441 Intrinsic argument(s) and/or return value have the wrong type.
3442 Erroneous code example:
3444 ```compile_fail,E0442
3445 #![feature(repr_simd)]
3446 #![feature(platform_intrinsics)]
3449 struct i8x16(i8, i8, i8, i8, i8, i8, i8, i8,
3450 i8, i8, i8, i8, i8, i8, i8, i8);
3452 struct i32x4(i32, i32, i32, i32);
3454 struct i64x2(i64, i64);
3456 extern "platform-intrinsic" {
3457 fn x86_mm_adds_epi16(x: i8x16, y: i32x4) -> i64x2;
3458 // error: intrinsic arguments/return value have wrong type
3462 To fix this error, please refer to the function declaration to give
3463 it the awaited types. Example:
3466 #![feature(repr_simd)]
3467 #![feature(platform_intrinsics)]
3470 struct i16x8(i16, i16, i16, i16, i16, i16, i16, i16);
3472 extern "platform-intrinsic" {
3473 fn x86_mm_adds_epi16(x: i16x8, y: i16x8) -> i16x8; // ok!
3479 Intrinsic argument(s) and/or return value have the wrong type.
3480 Erroneous code example:
3482 ```compile_fail,E0443
3483 #![feature(repr_simd)]
3484 #![feature(platform_intrinsics)]
3487 struct i16x8(i16, i16, i16, i16, i16, i16, i16, i16);
3489 struct i64x8(i64, i64, i64, i64, i64, i64, i64, i64);
3491 extern "platform-intrinsic" {
3492 fn x86_mm_adds_epi16(x: i16x8, y: i16x8) -> i64x8;
3493 // error: intrinsic argument/return value has wrong type
3497 To fix this error, please refer to the function declaration to give
3498 it the awaited types. Example:
3501 #![feature(repr_simd)]
3502 #![feature(platform_intrinsics)]
3505 struct i16x8(i16, i16, i16, i16, i16, i16, i16, i16);
3507 extern "platform-intrinsic" {
3508 fn x86_mm_adds_epi16(x: i16x8, y: i16x8) -> i16x8; // ok!
3514 A platform-specific intrinsic function has wrong number of arguments.
3515 Erroneous code example:
3517 ```compile_fail,E0444
3518 #![feature(repr_simd)]
3519 #![feature(platform_intrinsics)]
3522 struct f64x2(f64, f64);
3524 extern "platform-intrinsic" {
3525 fn x86_mm_movemask_pd(x: f64x2, y: f64x2, z: f64x2) -> i32;
3526 // error: platform-specific intrinsic has invalid number of arguments
3530 Please refer to the function declaration to see if it corresponds
3531 with yours. Example:
3534 #![feature(repr_simd)]
3535 #![feature(platform_intrinsics)]
3538 struct f64x2(f64, f64);
3540 extern "platform-intrinsic" {
3541 fn x86_mm_movemask_pd(x: f64x2) -> i32; // ok!
3547 The `typeof` keyword is currently reserved but unimplemented.
3548 Erroneous code example:
3550 ```compile_fail,E0516
3552 let x: typeof(92) = 92;
3556 Try using type inference instead. Example:
3566 A non-default implementation was already made on this type so it cannot be
3567 specialized further. Erroneous code example:
3569 ```compile_fail,E0520
3570 #![feature(specialization)]
3577 impl<T> SpaceLlama for T {
3578 default fn fly(&self) {}
3582 // applies to all `Clone` T and overrides the previous impl
3583 impl<T: Clone> SpaceLlama for T {
3587 // since `i32` is clone, this conflicts with the previous implementation
3588 impl SpaceLlama for i32 {
3589 default fn fly(&self) {}
3590 // error: item `fly` is provided by an `impl` that specializes
3591 // another, but the item in the parent `impl` is not marked
3592 // `default` and so it cannot be specialized.
3596 Specialization only allows you to override `default` functions in
3599 To fix this error, you need to mark all the parent implementations as default.
3603 #![feature(specialization)]
3610 impl<T> SpaceLlama for T {
3611 default fn fly(&self) {} // This is a parent implementation.
3614 // applies to all `Clone` T; overrides the previous impl
3615 impl<T: Clone> SpaceLlama for T {
3616 default fn fly(&self) {} // This is a parent implementation but was
3617 // previously not a default one, causing the error
3620 // applies to i32, overrides the previous two impls
3621 impl SpaceLlama for i32 {
3622 fn fly(&self) {} // And now that's ok!
3628 The number of elements in an array or slice pattern differed from the number of
3629 elements in the array being matched.
3631 Example of erroneous code:
3633 ```compile_fail,E0527
3634 let r = &[1, 2, 3, 4];
3636 &[a, b] => { // error: pattern requires 2 elements but array
3638 println!("a={}, b={}", a, b);
3643 Ensure that the pattern is consistent with the size of the matched
3644 array. Additional elements can be matched with `..`:
3647 #![feature(slice_patterns)]
3649 let r = &[1, 2, 3, 4];
3651 &[a, b, ..] => { // ok!
3652 println!("a={}, b={}", a, b);
3659 An array or slice pattern required more elements than were present in the
3662 Example of erroneous code:
3664 ```compile_fail,E0528
3665 #![feature(slice_patterns)]
3669 &[a, b, c, rest..] => { // error: pattern requires at least 3
3670 // elements but array has 2
3671 println!("a={}, b={}, c={} rest={:?}", a, b, c, rest);
3676 Ensure that the matched array has at least as many elements as the pattern
3677 requires. You can match an arbitrary number of remaining elements with `..`:
3680 #![feature(slice_patterns)]
3682 let r = &[1, 2, 3, 4, 5];
3684 &[a, b, c, rest..] => { // ok!
3685 // prints `a=1, b=2, c=3 rest=[4, 5]`
3686 println!("a={}, b={}, c={} rest={:?}", a, b, c, rest);
3693 An array or slice pattern was matched against some other type.
3695 Example of erroneous code:
3697 ```compile_fail,E0529
3700 [a, b] => { // error: expected an array or slice, found `f32`
3701 println!("a={}, b={}", a, b);
3706 Ensure that the pattern and the expression being matched on are of consistent
3713 println!("a={}, b={}", a, b);
3720 The `inline` attribute was malformed.
3722 Erroneous code example:
3724 ```ignore (compile_fail not working here; see Issue #43707)
3725 #[inline()] // error: expected one argument
3726 pub fn something() {}
3731 The parenthesized `inline` attribute requires the parameter to be specified:
3745 Alternatively, a paren-less version of the attribute may be used to hint the
3746 compiler about inlining opportunity:
3753 For more information about the inline attribute, read:
3754 https://doc.rust-lang.org/reference.html#inline-attributes
3758 An unknown argument was given to the `inline` attribute.
3760 Erroneous code example:
3762 ```ignore (compile_fail not working here; see Issue #43707)
3763 #[inline(unknown)] // error: invalid argument
3764 pub fn something() {}
3769 The `inline` attribute only supports two arguments:
3774 All other arguments given to the `inline` attribute will return this error.
3778 #[inline(never)] // ok!
3779 pub fn something() {}
3784 For more information about the inline attribute, https:
3785 read://doc.rust-lang.org/reference.html#inline-attributes
3789 The `export_name` attribute was malformed.
3791 Erroneous code example:
3793 ```ignore (error-emitted-at-codegen-which-cannot-be-handled-by-compile_fail)
3794 #[export_name] // error: `export_name` attribute has invalid format
3795 pub fn something() {}
3800 The `export_name` attribute expects a string in order to determine the name of
3801 the exported symbol. Example:
3804 #[export_name = "some_function"] // ok!
3805 pub fn something() {}
3812 An unknown field was specified into an enum's structure variant.
3814 Erroneous code example:
3816 ```compile_fail,E0559
3821 let s = Field::Fool { joke: 0 };
3822 // error: struct variant `Field::Fool` has no field named `joke`
3825 Verify you didn't misspell the field's name or that the field exists. Example:
3832 let s = Field::Fool { joke: 0 }; // ok!
3837 An unknown field was specified into a structure.
3839 Erroneous code example:
3841 ```compile_fail,E0560
3846 let s = Simba { mother: 1, father: 0 };
3847 // error: structure `Simba` has no field named `father`
3850 Verify you didn't misspell the field's name or that the field exists. Example:
3858 let s = Simba { mother: 1, father: 0 }; // ok!
3863 If an impl has a generic parameter with the `#[may_dangle]` attribute, then
3864 that impl must be declared as an `unsafe impl.
3866 Erroneous code example:
3868 ```compile_fail,E0569
3869 #![feature(dropck_eyepatch)]
3872 impl<#[may_dangle] X> Drop for Foo<X> {
3873 fn drop(&mut self) { }
3877 In this example, we are asserting that the destructor for `Foo` will not
3878 access any data of type `X`, and require this assertion to be true for
3879 overall safety in our program. The compiler does not currently attempt to
3880 verify this assertion; therefore we must tag this `impl` as unsafe.
3884 The requested ABI is unsupported by the current target.
3886 The rust compiler maintains for each target a blacklist of ABIs unsupported on
3887 that target. If an ABI is present in such a list this usually means that the
3888 target / ABI combination is currently unsupported by llvm.
3890 If necessary, you can circumvent this check using custom target specifications.
3894 A return statement was found outside of a function body.
3896 Erroneous code example:
3898 ```compile_fail,E0572
3899 const FOO: u32 = return 0; // error: return statement outside of function body
3904 To fix this issue, just remove the return keyword or move the expression into a
3910 fn some_fn() -> u32 {
3921 In a `fn` type, a lifetime appears only in the return type,
3922 and not in the arguments types.
3924 Erroneous code example:
3926 ```compile_fail,E0581
3928 // Here, `'a` appears only in the return type:
3929 let x: for<'a> fn() -> &'a i32;
3933 To fix this issue, either use the lifetime in the arguments, or use
3938 // Here, `'a` appears only in the return type:
3939 let x: for<'a> fn(&'a i32) -> &'a i32;
3940 let y: fn() -> &'static i32;
3944 Note: The examples above used to be (erroneously) accepted by the
3945 compiler, but this was since corrected. See [issue #33685] for more
3948 [issue #33685]: https://github.com/rust-lang/rust/issues/33685
3952 A lifetime appears only in an associated-type binding,
3953 and not in the input types to the trait.
3955 Erroneous code example:
3957 ```compile_fail,E0582
3959 // No type can satisfy this requirement, since `'a` does not
3960 // appear in any of the input types (here, `i32`):
3961 where F: for<'a> Fn(i32) -> Option<&'a i32>
3968 To fix this issue, either use the lifetime in the inputs, or use
3972 fn bar<F, G>(t: F, u: G)
3973 where F: for<'a> Fn(&'a i32) -> Option<&'a i32>,
3974 G: Fn(i32) -> Option<&'static i32>,
3981 Note: The examples above used to be (erroneously) accepted by the
3982 compiler, but this was since corrected. See [issue #33685] for more
3985 [issue #33685]: https://github.com/rust-lang/rust/issues/33685
3989 This error occurs when a method is used on a type which doesn't implement it:
3991 Erroneous code example:
3993 ```compile_fail,E0599
3997 x.chocolate(); // error: no method named `chocolate` found for type `Mouth`
3998 // in the current scope
4003 An unary operator was used on a type which doesn't implement it.
4005 Example of erroneous code:
4007 ```compile_fail,E0600
4013 !Question::Yes; // error: cannot apply unary operator `!` to type `Question`
4016 In this case, `Question` would need to implement the `std::ops::Not` trait in
4017 order to be able to use `!` on it. Let's implement it:
4027 // We implement the `Not` trait on the enum.
4028 impl Not for Question {
4031 fn not(self) -> bool {
4033 Question::Yes => false, // If the `Answer` is `Yes`, then it
4035 Question::No => true, // And here we do the opposite.
4040 assert_eq!(!Question::Yes, false);
4041 assert_eq!(!Question::No, true);
4046 An attempt to index into a type which doesn't implement the `std::ops::Index`
4047 trait was performed.
4049 Erroneous code example:
4051 ```compile_fail,E0608
4052 0u8[2]; // error: cannot index into a value of type `u8`
4055 To be able to index into a type it needs to implement the `std::ops::Index`
4059 let v: Vec<u8> = vec![0, 1, 2, 3];
4061 // The `Vec` type implements the `Index` trait so you can do:
4062 println!("{}", v[2]);
4067 A cast to `char` was attempted on a type other than `u8`.
4069 Erroneous code example:
4071 ```compile_fail,E0604
4072 0u32 as char; // error: only `u8` can be cast as `char`, not `u32`
4075 As the error message indicates, only `u8` can be cast into `char`. Example:
4078 let c = 86u8 as char; // ok!
4082 For more information about casts, take a look at The Book:
4083 https://doc.rust-lang.org/book/first-edition/casting-between-types.html
4087 An invalid cast was attempted.
4089 Erroneous code examples:
4091 ```compile_fail,E0605
4093 x as Vec<u8>; // error: non-primitive cast: `u8` as `std::vec::Vec<u8>`
4097 let v = 0 as *const u8; // So here, `v` is a `*const u8`.
4098 v as &u8; // error: non-primitive cast: `*const u8` as `&u8`
4101 Only primitive types can be cast into each other. Examples:
4107 let v = 0 as *const u8;
4108 v as *const i8; // ok!
4111 For more information about casts, take a look at The Book:
4112 https://doc.rust-lang.org/book/first-edition/casting-between-types.html
4116 An incompatible cast was attempted.
4118 Erroneous code example:
4120 ```compile_fail,E0606
4121 let x = &0u8; // Here, `x` is a `&u8`.
4122 let y: u32 = x as u32; // error: casting `&u8` as `u32` is invalid
4125 When casting, keep in mind that only primitive types can be cast into each
4130 let y: u32 = *x as u32; // We dereference it first and then cast it.
4133 For more information about casts, take a look at The Book:
4134 https://doc.rust-lang.org/book/first-edition/casting-between-types.html
4138 A cast between a thin and a fat pointer was attempted.
4140 Erroneous code example:
4142 ```compile_fail,E0607
4143 let v = 0 as *const u8;
4147 First: what are thin and fat pointers?
4149 Thin pointers are "simple" pointers: they are purely a reference to a memory
4152 Fat pointers are pointers referencing Dynamically Sized Types (also called DST).
4153 DST don't have a statically known size, therefore they can only exist behind
4154 some kind of pointers that contain additional information. Slices and trait
4155 objects are DSTs. In the case of slices, the additional information the fat
4156 pointer holds is their size.
4158 To fix this error, don't try to cast directly between thin and fat pointers.
4160 For more information about casts, take a look at The Book:
4161 https://doc.rust-lang.org/book/first-edition/casting-between-types.html
4165 Attempted to access a non-existent field in a struct.
4167 Erroneous code example:
4169 ```compile_fail,E0609
4170 struct StructWithFields {
4174 let s = StructWithFields { x: 0 };
4175 println!("{}", s.foo); // error: no field `foo` on type `StructWithFields`
4178 To fix this error, check that you didn't misspell the field's name or that the
4179 field actually exists. Example:
4182 struct StructWithFields {
4186 let s = StructWithFields { x: 0 };
4187 println!("{}", s.x); // ok!
4192 Attempted to access a field on a primitive type.
4194 Erroneous code example:
4196 ```compile_fail,E0610
4198 println!("{}", x.foo); // error: `{integer}` is a primitive type, therefore
4199 // doesn't have fields
4202 Primitive types are the most basic types available in Rust and don't have
4203 fields. To access data via named fields, struct types are used. Example:
4206 // We declare struct called `Foo` containing two fields:
4212 // We create an instance of this struct:
4213 let variable = Foo { x: 0, y: -12 };
4214 // And we can now access its fields:
4215 println!("x: {}, y: {}", variable.x, variable.y);
4218 For more information about primitives and structs, take a look at The Book:
4219 https://doc.rust-lang.org/book/first-edition/primitive-types.html
4220 https://doc.rust-lang.org/book/first-edition/structs.html
4224 Attempted to dereference a variable which cannot be dereferenced.
4226 Erroneous code example:
4228 ```compile_fail,E0614
4230 *y; // error: type `u32` cannot be dereferenced
4233 Only types implementing `std::ops::Deref` can be dereferenced (such as `&T`).
4239 // So here, `x` is a `&u32`, so we can dereference it:
4245 Attempted to access a method like a field.
4247 Erroneous code example:
4249 ```compile_fail,E0615
4258 let f = Foo { x: 0 };
4259 f.method; // error: attempted to take value of method `method` on type `Foo`
4262 If you want to use a method, add `()` after it:
4265 # struct Foo { x: u32 }
4266 # impl Foo { fn method(&self) {} }
4267 # let f = Foo { x: 0 };
4271 However, if you wanted to access a field of a struct check that the field name
4272 is spelled correctly. Example:
4275 # struct Foo { x: u32 }
4276 # impl Foo { fn method(&self) {} }
4277 # let f = Foo { x: 0 };
4278 println!("{}", f.x);
4283 Attempted to access a private field on a struct.
4285 Erroneous code example:
4287 ```compile_fail,E0616
4290 x: u32, // So `x` is private in here.
4294 pub fn new() -> Foo { Foo { x: 0 } }
4298 let f = some_module::Foo::new();
4299 println!("{}", f.x); // error: field `x` of struct `some_module::Foo` is private
4302 If you want to access this field, you have two options:
4304 1) Set the field public:
4309 pub x: u32, // `x` is now public.
4313 pub fn new() -> Foo { Foo { x: 0 } }
4317 let f = some_module::Foo::new();
4318 println!("{}", f.x); // ok!
4321 2) Add a getter function:
4326 x: u32, // So `x` is still private in here.
4330 pub fn new() -> Foo { Foo { x: 0 } }
4332 // We create the getter function here:
4333 pub fn get_x(&self) -> &u32 { &self.x }
4337 let f = some_module::Foo::new();
4338 println!("{}", f.get_x()); // ok!
4343 Attempted to pass an invalid type of variable into a variadic function.
4345 Erroneous code example:
4347 ```compile_fail,E0617
4349 fn printf(c: *const i8, ...);
4353 printf(::std::ptr::null(), 0f32);
4354 // error: can't pass an `f32` to variadic function, cast to `c_double`
4358 Certain Rust types must be cast before passing them to a variadic function,
4359 because of arcane ABI rules dictated by the C standard. To fix the error,
4360 cast the value to the type specified by the error message (which you may need
4361 to import from `std::os::raw`).
4365 Attempted to call something which isn't a function nor a method.
4367 Erroneous code examples:
4369 ```compile_fail,E0618
4374 X::Entry(); // error: expected function, found `X::Entry`
4378 x(); // error: expected function, found `i32`
4381 Only functions and methods can be called using `()`. Example:
4384 // We declare a function:
4385 fn i_am_a_function() {}
4393 #### Note: this error code is no longer emitted by the compiler.
4394 The type-checker needed to know the type of an expression, but that type had not
4397 Erroneous code example:
4403 // Here, the type of `v` is not (yet) known, so we
4404 // cannot resolve this method call:
4405 v.to_uppercase(); // error: the type of this value must be known in
4412 Type inference typically proceeds from the top of the function to the bottom,
4413 figuring out types as it goes. In some cases -- notably method calls and
4414 overloadable operators like `*` -- the type checker may not have enough
4415 information *yet* to make progress. This can be true even if the rest of the
4416 function provides enough context (because the type-checker hasn't looked that
4417 far ahead yet). In this case, type annotations can be used to help it along.
4419 To fix this error, just specify the type of the variable. Example:
4422 let mut x: Vec<String> = vec![]; // We precise the type of the vec elements.
4425 v.to_uppercase(); // Since rustc now knows the type of the vec elements,
4426 // we can use `v`'s methods.
4434 A cast to an unsized type was attempted.
4436 Erroneous code example:
4438 ```compile_fail,E0620
4439 let x = &[1_usize, 2] as [usize]; // error: cast to unsized type: `&[usize; 2]`
4443 In Rust, some types don't have a known size at compile-time. For example, in a
4444 slice type like `[u32]`, the number of elements is not known at compile-time and
4445 hence the overall size cannot be computed. As a result, such types can only be
4446 manipulated through a reference (e.g., `&T` or `&mut T`) or other pointer-type
4447 (e.g., `Box` or `Rc`). Try casting to a reference instead:
4450 let x = &[1_usize, 2] as &[usize]; // ok!
4455 An intrinsic was declared without being a function.
4457 Erroneous code example:
4459 ```compile_fail,E0622
4460 #![feature(intrinsics)]
4461 extern "rust-intrinsic" {
4462 pub static breakpoint : unsafe extern "rust-intrinsic" fn();
4463 // error: intrinsic must be a function
4466 fn main() { unsafe { breakpoint(); } }
4469 An intrinsic is a function available for use in a given programming language
4470 whose implementation is handled specially by the compiler. In order to fix this
4471 error, just declare a function.
4475 A private item was used outside of its scope.
4477 Erroneous code example:
4479 ```compile_fail,E0624
4488 let foo = inner::Foo;
4489 foo.method(); // error: method `method` is private
4492 Two possibilities are available to solve this issue:
4494 1. Only use the item in the scope it has been defined:
4504 pub fn call_method(foo: &Foo) { // We create a public function.
4505 foo.method(); // Which calls the item.
4509 let foo = inner::Foo;
4510 inner::call_method(&foo); // And since the function is public, we can call the
4511 // method through it.
4514 2. Make the item public:
4521 pub fn method(&self) {} // It's now public.
4525 let foo = inner::Foo;
4526 foo.method(); // Ok!
4531 This error indicates that the struct or enum must be matched non-exhaustively
4532 as it has been marked as `non_exhaustive`.
4534 When applied within a crate, downstream users of the crate will need to use the
4535 `_` pattern when matching enums and use the `..` pattern when matching structs.
4537 For example, in the below example, since the enum is marked as
4538 `non_exhaustive`, it is required that downstream crates match non-exhaustively
4541 ```rust,ignore (pseudo-Rust)
4542 use std::error::Error as StdError;
4544 #[non_exhaustive] pub enum Error {
4549 impl StdError for Error {
4550 fn description(&self) -> &str {
4551 // This will not error, despite being marked as non_exhaustive, as this
4552 // enum is defined within the current crate, it can be matched
4555 Message(ref s) => s,
4556 Other => "other or unknown error",
4562 An example of matching non-exhaustively on the above enum is provided below:
4564 ```rust,ignore (pseudo-Rust)
4567 // This will not error as the non_exhaustive Error enum has been matched with a
4570 Message(ref s) => ...,
4576 Similarly, for structs, match with `..` to avoid this error.
4580 This error indicates that the struct or enum cannot be instantiated from
4581 outside of the defining crate as it has been marked as `non_exhaustive` and as
4582 such more fields/variants may be added in future that could cause adverse side
4583 effects for this code.
4585 It is recommended that you look for a `new` function or equivalent in the
4586 crate's documentation.
4590 This error indicates that there is a mismatch between generic parameters and
4591 impl Trait parameters in a trait declaration versus its impl.
4593 ```compile_fail,E0643
4595 fn foo(&self, _: &impl Iterator);
4598 fn foo<U: Iterator>(&self, _: &U) { } // error method `foo` has incompatible
4599 // signature for trait
4605 It is not possible to define `main` with a where clause.
4606 Erroneous code example:
4608 ```compile_fail,E0646
4609 fn main() where i32: Copy { // error: main function is not allowed to have
4616 It is not possible to define `start` with a where clause.
4617 Erroneous code example:
4619 ```compile_fail,E0647
4623 fn start(_: isize, _: *const *const u8) -> isize where (): Copy {
4624 //^ error: start function is not allowed to have a where clause
4631 `export_name` attributes may not contain null characters (`\0`).
4633 ```compile_fail,E0648
4634 #[export_name="\0foo"] // error: `export_name` may not contain null characters
4640 This error indicates that the numeric value for the method being passed exists
4641 but the type of the numeric value or binding could not be identified.
4643 The error happens on numeric literals:
4645 ```compile_fail,E0689
4649 and on numeric bindings without an identified concrete type:
4651 ```compile_fail,E0689
4653 x.neg(); // same error as above
4656 Because of this, you must give the numeric literal or binding a type:
4661 let _ = 2.0_f32.neg();
4664 let _ = (2.0 as f32).neg();
4669 A struct with the representation hint `repr(transparent)` had zero or more than
4670 on fields that were not guaranteed to be zero-sized.
4672 Erroneous code example:
4674 ```compile_fail,E0690
4675 #[repr(transparent)]
4676 struct LengthWithUnit<U> { // error: transparent struct needs exactly one
4677 value: f32, // non-zero-sized field, but has 2
4682 Because transparent structs are represented exactly like one of their fields at
4683 run time, said field must be uniquely determined. If there is no field, or if
4684 there are multiple fields, it is not clear how the struct should be represented.
4685 Note that fields of zero-typed types (e.g., `PhantomData`) can also exist
4686 alongside the field that contains the actual data, they do not count for this
4687 error. When generic types are involved (as in the above example), an error is
4688 reported because the type parameter could be non-zero-sized.
4690 To combine `repr(transparent)` with type parameters, `PhantomData` may be
4694 use std::marker::PhantomData;
4696 #[repr(transparent)]
4697 struct LengthWithUnit<U> {
4699 unit: PhantomData<U>,
4705 A struct with the `repr(transparent)` representation hint contains a zero-sized
4706 field that requires non-trivial alignment.
4708 Erroneous code example:
4710 ```compile_fail,E0691
4711 #![feature(repr_align)]
4714 struct ForceAlign32;
4716 #[repr(transparent)]
4717 struct Wrapper(f32, ForceAlign32); // error: zero-sized field in transparent
4718 // struct has alignment larger than 1
4721 A transparent struct is supposed to be represented exactly like the piece of
4722 data it contains. Zero-sized fields with different alignment requirements
4723 potentially conflict with this property. In the example above, `Wrapper` would
4724 have to be aligned to 32 bytes even though `f32` has a smaller alignment
4727 Consider removing the over-aligned zero-sized field:
4730 #[repr(transparent)]
4731 struct Wrapper(f32);
4734 Alternatively, `PhantomData<T>` has alignment 1 for all `T`, so you can use it
4735 if you need to keep the field for some reason:
4738 #![feature(repr_align)]
4740 use std::marker::PhantomData;
4743 struct ForceAlign32;
4745 #[repr(transparent)]
4746 struct Wrapper(f32, PhantomData<ForceAlign32>);
4749 Note that empty arrays `[T; 0]` have the same alignment requirement as the
4750 element type `T`. Also note that the error is conservatively reported even when
4751 the alignment of the zero-sized type is less than or equal to the data field's
4757 A method was called on a raw pointer whose inner type wasn't completely known.
4759 For example, you may have done something like:
4762 # #![deny(warnings)]
4764 let bar = foo as *const _;
4770 Here, the type of `bar` isn't known; it could be a pointer to anything. Instead,
4771 specify a type for the pointer (preferably something that makes sense for the
4772 thing you're pointing to):
4776 let bar = foo as *const i32;
4782 Even though `is_null()` exists as a method on any raw pointer, Rust shows this
4783 error because Rust allows for `self` to have arbitrary types (behind the
4784 arbitrary_self_types feature flag).
4786 This means that someone can specify such a function:
4788 ```ignore (cannot-doctest-feature-doesnt-exist-yet)
4790 fn is_null(self: *const Self) -> bool {
4791 // do something else
4796 and now when you call `.is_null()` on a raw pointer to `Foo`, there's ambiguity.
4798 Given that we don't know what type the pointer is, and there's potential
4799 ambiguity for some types, we disallow calling methods on raw pointers when
4800 the type is unknown.
4804 A `#[marker]` trait contained an associated item.
4806 The items of marker traits cannot be overridden, so there's no need to have them
4807 when they cannot be changed per-type anyway. If you wanted them for ergonomic
4808 reasons, consider making an extension trait instead.
4812 An `impl` for a `#[marker]` trait tried to override an associated item.
4814 Because marker traits are allowed to have multiple implementations for the same
4815 type, it's not allowed to override anything in those implementations, as it
4816 would be ambiguous which override should actually be used.
4821 An `impl Trait` type expands to a recursive type.
4823 An `impl Trait` type must be expandable to a concrete type that contains no
4824 `impl Trait` types. For example the following example tries to create an
4825 `impl Trait` type `T` that is equal to `[T, T]`:
4827 ```compile_fail,E0720
4828 fn make_recursive_type() -> impl Sized {
4829 [make_recursive_type(), make_recursive_type()]
4836 register_diagnostics! {
4837 // E0035, merged into E0087/E0089
4838 // E0036, merged into E0087/E0089
4844 // E0122, // bounds in type aliases are ignored, turned into proper lint
4849 // E0159, // use of trait `{}` as struct constructor
4850 // E0163, // merged into E0071
4853 // E0172, // non-trait found in a type sum, moved to resolve
4854 // E0173, // manual implementations of unboxed closure traits are experimental
4856 // E0182, // merged into E0229
4858 // E0187, // can't infer the kind of the closure
4859 // E0188, // can not cast an immutable reference to a mutable pointer
4860 // E0189, // deprecated: can only cast a boxed pointer to a boxed object
4861 // E0190, // deprecated: can only cast a &-pointer to an &-object
4862 // E0196, // cannot determine a type for this closure
4863 E0203, // type parameter has more than one relaxed default bound,
4864 // and only one is supported
4866 // E0209, // builtin traits can only be implemented on structs or enums
4867 E0212, // cannot extract an associated type from a higher-ranked trait bound
4868 // E0213, // associated types are not accepted in this context
4869 // E0215, // angle-bracket notation is not stable with `Fn`
4870 // E0216, // parenthetical notation is only stable with `Fn`
4871 // E0217, // ambiguous associated type, defined in multiple supertraits
4872 // E0218, // no associated type defined
4873 // E0219, // associated type defined in higher-ranked supertrait
4874 // E0222, // Error code E0045 (variadic function must have C or cdecl calling
4875 // convention) duplicate
4876 E0224, // at least one non-builtin train is required for an object type
4877 E0227, // ambiguous lifetime bound, explicit lifetime bound required
4878 E0228, // explicit lifetime bound required
4881 // E0235, // structure constructor specifies a structure of type but
4882 // E0236, // no lang item for range syntax
4883 // E0237, // no lang item for range syntax
4884 // E0238, // parenthesized parameters may only be used with a trait
4885 // E0239, // `next` method of `Iterator` trait has unexpected type
4889 // E0245, // not a trait
4890 // E0246, // invalid recursive type
4892 // E0248, // value used as a type, now reported earlier during resolution as E0412
4894 E0307, // invalid method `self` type
4895 // E0319, // trait impls for defaulted traits allowed just for structs/enums
4896 // E0372, // coherence not object safe
4897 E0377, // the trait `CoerceUnsized` may only be implemented for a coercion
4898 // between structures with the same definition
4899 E0533, // `{}` does not name a unit variant, unit struct or a constant
4900 // E0563, // cannot determine a type for this `impl Trait`: {} // removed in 6383de15
4901 E0564, // only named lifetimes are allowed in `impl Trait`,
4902 // but `{}` was found in the type `{}`
4903 E0587, // type has conflicting packed and align representation hints
4904 E0588, // packed type cannot transitively contain a `[repr(align)]` type
4905 E0592, // duplicate definitions with name `{}`
4906 // E0611, // merged into E0616
4907 // E0612, // merged into E0609
4908 // E0613, // Removed (merged with E0609)
4909 E0627, // yield statement outside of generator literal
4910 E0632, // cannot provide explicit type parameters when `impl Trait` is used in
4911 // argument position.
4912 E0634, // type has conflicting packed representaton hints
4913 E0640, // infer outlives requirements
4914 E0641, // cannot cast to/from a pointer with an unknown kind
4915 E0645, // trait aliases not finished
4916 E0698, // type inside generator must be known in this context
4917 E0719, // duplicate values for associated type binding