1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![allow(non_snake_case)]
13 register_long_diagnostics! {
16 A pattern used to match against an enum variant must provide a sub-pattern for
17 each field of the enum variant. This error indicates that a pattern attempted to
18 extract an incorrect number of fields from a variant.
22 Apple(String, String),
27 Here the `Apple` variant has two fields, and should be matched against like so:
31 Apple(String, String),
35 let x = Fruit::Apple(String::new(), String::new());
39 Fruit::Apple(a, b) => {},
44 Matching with the wrong number of fields has no sensible interpretation:
48 Apple(String, String),
52 let x = Fruit::Apple(String::new(), String::new());
56 Fruit::Apple(a) => {},
57 Fruit::Apple(a, b, c) => {},
61 Check how many fields the enum was declared with and ensure that your pattern
66 Each field of a struct can only be bound once in a pattern. Erroneous code
76 let x = Foo { a:1, b:2 };
78 let Foo { a: x, a: y } = x;
79 // error: field `a` bound multiple times in the pattern
83 Each occurrence of a field name binds the value of that field, so to fix this
84 error you will have to remove or alter the duplicate uses of the field name.
85 Perhaps you misspelled another field name? Example:
94 let x = Foo { a:1, b:2 };
96 let Foo { a: x, b: y } = x; // ok!
102 This error indicates that a struct pattern attempted to extract a non-existent
103 field from a struct. Struct fields are identified by the name used before the
104 colon `:` so struct patterns should resemble the declaration of the struct type
114 let thing = Thing { x: 1, y: 2 };
117 Thing { x: xfield, y: yfield } => {}
121 If you are using shorthand field patterns but want to refer to the struct field
122 by a different name, you should rename it explicitly.
126 ```compile_fail,E0026
132 let thing = Thing { x: 0, y: 0 };
147 let thing = Thing { x: 0, y: 0 };
150 Thing { x, y: z } => {}
156 This error indicates that a pattern for a struct fails to specify a sub-pattern
157 for every one of the struct's fields. Ensure that each field from the struct's
158 definition is mentioned in the pattern, or use `..` to ignore unwanted fields.
162 ```compile_fail,E0027
168 let d = Dog { name: "Rusty".to_string(), age: 8 };
170 // This is incorrect.
176 This is correct (explicit):
184 let d = Dog { name: "Rusty".to_string(), age: 8 };
187 Dog { name: ref n, age: x } => {}
190 // This is also correct (ignore unused fields).
192 Dog { age: x, .. } => {}
198 In a match expression, only numbers and characters can be matched against a
199 range. This is because the compiler checks that the range is non-empty at
200 compile-time, and is unable to evaluate arbitrary comparison functions. If you
201 want to capture values of an orderable type between two end-points, you can use
204 ```compile_fail,E0029
205 let string = "salutations !";
207 // The ordering relation for strings can't be evaluated at compile time,
208 // so this doesn't work:
210 "hello" ..= "world" => {}
214 // This is a more general version, using a guard:
216 s if s >= "hello" && s <= "world" => {}
223 This error indicates that a pointer to a trait type cannot be implicitly
224 dereferenced by a pattern. Every trait defines a type, but because the
225 size of trait implementors isn't fixed, this type has no compile-time size.
226 Therefore, all accesses to trait types must be through pointers. If you
227 encounter this error you should try to avoid dereferencing the pointer.
229 ```compile_fail,E0033
230 # trait SomeTrait { fn method_one(&self){} fn method_two(&self){} }
231 # impl<T> SomeTrait for T {}
232 let trait_obj: &SomeTrait = &"some_value";
234 // This tries to implicitly dereference to create an unsized local variable.
235 let &invalid = trait_obj;
237 // You can call methods without binding to the value being pointed at.
238 trait_obj.method_one();
239 trait_obj.method_two();
242 You can read more about trait objects in the [Trait Objects] section of the
245 [Trait Objects]: https://doc.rust-lang.org/reference/types.html#trait-objects
249 The compiler doesn't know what method to call because more than one method
250 has the same prototype. Erroneous code example:
252 ```compile_fail,E0034
263 impl Trait1 for Test { fn foo() {} }
264 impl Trait2 for Test { fn foo() {} }
267 Test::foo() // error, which foo() to call?
271 To avoid this error, you have to keep only one of them and remove the others.
272 So let's take our example and fix it:
281 impl Trait1 for Test { fn foo() {} }
284 Test::foo() // and now that's good!
288 However, a better solution would be using fully explicit naming of type and
302 impl Trait1 for Test { fn foo() {} }
303 impl Trait2 for Test { fn foo() {} }
306 <Test as Trait1>::foo()
323 impl F for X { fn m(&self) { println!("I am F"); } }
324 impl G for X { fn m(&self) { println!("I am G"); } }
329 F::m(&f); // it displays "I am F"
330 G::m(&f); // it displays "I am G"
336 It is not allowed to manually call destructors in Rust. It is also not
337 necessary to do this since `drop` is called automatically whenever a value goes
340 Here's an example of this error:
342 ```compile_fail,E0040
354 let mut x = Foo { x: -7 };
355 x.drop(); // error: explicit use of destructor method
361 You can't use type parameters on foreign items. Example of erroneous code:
363 ```compile_fail,E0044
364 extern { fn some_func<T>(x: T); }
367 To fix this, replace the type parameter with the specializations that you
371 extern { fn some_func_i32(x: i32); }
372 extern { fn some_func_i64(x: i64); }
377 Rust only supports variadic parameters for interoperability with C code in its
378 FFI. As such, variadic parameters can only be used with functions which are
379 using the C ABI. Examples of erroneous code:
382 #![feature(unboxed_closures)]
384 extern "rust-call" { fn foo(x: u8, ...); }
388 fn foo(x: u8, ...) {}
391 To fix such code, put them in an extern "C" block:
401 Items are missing in a trait implementation. Erroneous code example:
403 ```compile_fail,E0046
411 // error: not all trait items implemented, missing: `foo`
414 When trying to make some type implement a trait `Foo`, you must, at minimum,
415 provide implementations for all of `Foo`'s required methods (meaning the
416 methods that do not have default implementations), as well as any required
417 trait items like associated types or constants. Example:
433 This error indicates that an attempted implementation of a trait method
434 has the wrong number of type parameters.
436 For example, the trait below has a method `foo` with a type parameter `T`,
437 but the implementation of `foo` for the type `Bar` is missing this parameter:
439 ```compile_fail,E0049
441 fn foo<T: Default>(x: T) -> Self;
446 // error: method `foo` has 0 type parameters but its trait declaration has 1
449 fn foo(x: bool) -> Self { Bar }
455 This error indicates that an attempted implementation of a trait method
456 has the wrong number of function parameters.
458 For example, the trait below has a method `foo` with two function parameters
459 (`&self` and `u8`), but the implementation of `foo` for the type `Bar` omits
462 ```compile_fail,E0050
464 fn foo(&self, x: u8) -> bool;
469 // error: method `foo` has 1 parameter but the declaration in trait `Foo::foo`
472 fn foo(&self) -> bool { true }
478 The parameters of any trait method must match between a trait implementation
479 and the trait definition.
481 Here are a couple examples of this error:
483 ```compile_fail,E0053
492 // error, expected u16, found i16
495 // error, types differ in mutability
496 fn bar(&mut self) { }
502 It is not allowed to cast to a bool. If you are trying to cast a numeric type
503 to a bool, you can compare it with zero instead:
505 ```compile_fail,E0054
508 // Not allowed, won't compile
509 let x_is_nonzero = x as bool;
516 let x_is_nonzero = x != 0;
521 During a method call, a value is automatically dereferenced as many times as
522 needed to make the value's type match the method's receiver. The catch is that
523 the compiler will only attempt to dereference a number of times up to the
524 recursion limit (which can be set via the `recursion_limit` attribute).
526 For a somewhat artificial example:
528 ```compile_fail,E0055
529 #![recursion_limit="2"]
541 // error, reached the recursion limit while auto-dereferencing `&&Foo`
546 One fix may be to increase the recursion limit. Note that it is possible to
547 create an infinite recursion of dereferencing, in which case the only fix is to
548 somehow break the recursion.
552 When invoking closures or other implementations of the function traits `Fn`,
553 `FnMut` or `FnOnce` using call notation, the number of parameters passed to the
554 function must match its definition.
556 An example using a closure:
558 ```compile_fail,E0057
560 let a = f(); // invalid, too few parameters
561 let b = f(4); // this works!
562 let c = f(2, 3); // invalid, too many parameters
565 A generic function must be treated similarly:
568 fn foo<F: Fn()>(f: F) {
569 f(); // this is valid, but f(3) would not work
575 The built-in function traits are generic over a tuple of the function arguments.
576 If one uses angle-bracket notation (`Fn<(T,), Output=U>`) instead of parentheses
577 (`Fn(T) -> U`) to denote the function trait, the type parameter should be a
578 tuple. Otherwise function call notation cannot be used and the trait will not be
579 implemented by closures.
581 The most likely source of this error is using angle-bracket notation without
582 wrapping the function argument type into a tuple, for example:
584 ```compile_fail,E0059
585 #![feature(unboxed_closures)]
587 fn foo<F: Fn<i32>>(f: F) -> F::Output { f(3) }
590 It can be fixed by adjusting the trait bound like this:
593 #![feature(unboxed_closures)]
595 fn foo<F: Fn<(i32,)>>(f: F) -> F::Output { f(3) }
598 Note that `(T,)` always denotes the type of a 1-tuple containing an element of
599 type `T`. The comma is necessary for syntactic disambiguation.
603 External C functions are allowed to be variadic. However, a variadic function
604 takes a minimum number of arguments. For example, consider C's variadic `printf`
608 use std::os::raw::{c_char, c_int};
611 fn printf(_: *const c_char, ...) -> c_int;
615 Using this declaration, it must be called with at least one argument, so
616 simply calling `printf()` is invalid. But the following uses are allowed:
619 # #![feature(static_nobundle)]
620 # use std::os::raw::{c_char, c_int};
621 # #[cfg_attr(all(windows, target_env = "msvc"),
622 # link(name = "legacy_stdio_definitions", kind = "static-nobundle"))]
623 # extern "C" { fn printf(_: *const c_char, ...) -> c_int; }
626 use std::ffi::CString;
628 let fmt = CString::new("test\n").unwrap();
629 printf(fmt.as_ptr());
631 let fmt = CString::new("number = %d\n").unwrap();
632 printf(fmt.as_ptr(), 3);
634 let fmt = CString::new("%d, %d\n").unwrap();
635 printf(fmt.as_ptr(), 10, 5);
640 // ^ Note: On MSVC 2015, the `printf` function is "inlined" in the C code, and
641 // the C runtime does not contain the `printf` definition. This leads to linker
642 // error from the doc test (issue #42830).
643 // This can be fixed by linking to the static library
644 // `legacy_stdio_definitions.lib` (see https://stackoverflow.com/a/36504365/).
645 // If this compatibility library is removed in the future, consider changing
646 // `printf` in this example to another well-known variadic function.
649 The number of arguments passed to a function must match the number of arguments
650 specified in the function signature.
652 For example, a function like:
655 fn f(a: u16, b: &str) {}
658 Must always be called with exactly two arguments, e.g., `f(2, "test")`.
660 Note that Rust does not have a notion of optional function arguments or
661 variadic functions (except for its C-FFI).
665 This error indicates that during an attempt to build a struct or struct-like
666 enum variant, one of the fields was specified more than once. Erroneous code
669 ```compile_fail,E0062
677 x: 0, // error: field `x` specified more than once
682 Each field should be specified exactly one time. Example:
690 let x = Foo { x: 0 }; // ok!
696 This error indicates that during an attempt to build a struct or struct-like
697 enum variant, one of the fields was not provided. Erroneous code example:
699 ```compile_fail,E0063
706 let x = Foo { x: 0 }; // error: missing field: `y`
710 Each field should be specified exactly once. Example:
719 let x = Foo { x: 0, y: 0 }; // ok!
725 The left-hand side of a compound assignment expression must be a place
726 expression. A place expression represents a memory location and includes
727 item paths (ie, namespaced variables), dereferences, indexing expressions,
728 and field references.
730 Let's start with some erroneous code examples:
732 ```compile_fail,E0067
733 use std::collections::LinkedList;
735 // Bad: assignment to non-place expression
736 LinkedList::new() += 1;
740 fn some_func(i: &mut i32) {
741 i += 12; // Error : '+=' operation cannot be applied on a reference !
745 And now some working examples:
754 fn some_func(i: &mut i32) {
761 The compiler found a function whose body contains a `return;` statement but
762 whose return type is not `()`. An example of this is:
764 ```compile_fail,E0069
771 Since `return;` is just like `return ();`, there is a mismatch between the
772 function's return type and the value being returned.
776 The left-hand side of an assignment operator must be a place expression. An
777 place expression represents a memory location and can be a variable (with
778 optional namespacing), a dereference, an indexing expression or a field
781 More details can be found in the [Expressions] section of the Reference.
783 [Expressions]: https://doc.rust-lang.org/reference/expressions.html#places-rvalues-and-temporaries
785 Now, we can go further. Here are some erroneous code examples:
787 ```compile_fail,E0070
793 const SOME_CONST : i32 = 12;
795 fn some_other_func() {}
798 SOME_CONST = 14; // error : a constant value cannot be changed!
799 1 = 3; // error : 1 isn't a valid place!
800 some_other_func() = 4; // error : we can't assign value to a function!
801 SomeStruct.x = 12; // error : SomeStruct a structure name but it is used
806 And now let's give working examples:
813 let mut s = SomeStruct {x: 0, y: 0};
815 s.x = 3; // that's good !
819 fn some_func(x: &mut i32) {
820 *x = 12; // that's good !
826 You tried to use structure-literal syntax to create an item that is
827 not a structure or enum variant.
829 Example of erroneous code:
831 ```compile_fail,E0071
833 let t = U32 { value: 4 }; // error: expected struct, variant or union type,
834 // found builtin type `u32`
837 To fix this, ensure that the name was correctly spelled, and that
838 the correct form of initializer was used.
840 For example, the code above can be fixed to:
848 let u = Foo::FirstValue(0i32);
856 #### Note: this error code is no longer emitted by the compiler.
858 You cannot define a struct (or enum) `Foo` that requires an instance of `Foo`
859 in order to make a new `Foo` value. This is because there would be no way a
860 first instance of `Foo` could be made to initialize another instance!
862 Here's an example of a struct that has this problem:
865 struct Foo { x: Box<Foo> } // error
868 One fix is to use `Option`, like so:
871 struct Foo { x: Option<Box<Foo>> }
874 Now it's possible to create at least one instance of `Foo`: `Foo { x: None }`.
878 #### Note: this error code is no longer emitted by the compiler.
880 When using the `#[simd]` attribute on a tuple struct, the components of the
881 tuple struct must all be of a concrete, nongeneric type so the compiler can
882 reason about how to use SIMD with them. This error will occur if the types
885 This will cause an error:
888 #![feature(repr_simd)]
891 struct Bad<T>(T, T, T);
897 #![feature(repr_simd)]
900 struct Good(u32, u32, u32);
905 The `#[simd]` attribute can only be applied to non empty tuple structs, because
906 it doesn't make sense to try to use SIMD operations when there are no values to
909 This will cause an error:
911 ```compile_fail,E0075
912 #![feature(repr_simd)]
921 #![feature(repr_simd)]
929 When using the `#[simd]` attribute to automatically use SIMD operations in tuple
930 struct, the types in the struct must all be of the same type, or the compiler
931 will trigger this error.
933 This will cause an error:
935 ```compile_fail,E0076
936 #![feature(repr_simd)]
939 struct Bad(u16, u32, u32);
945 #![feature(repr_simd)]
948 struct Good(u32, u32, u32);
953 When using the `#[simd]` attribute on a tuple struct, the elements in the tuple
954 must be machine types so SIMD operations can be applied to them.
956 This will cause an error:
958 ```compile_fail,E0077
959 #![feature(repr_simd)]
968 #![feature(repr_simd)]
971 struct Good(u32, u32, u32);
976 Enum discriminants are used to differentiate enum variants stored in memory.
977 This error indicates that the same value was used for two or more variants,
978 making them impossible to tell apart.
980 ```compile_fail,E0081
998 Note that variants without a manually specified discriminant are numbered from
999 top to bottom starting from 0, so clashes can occur with seemingly unrelated
1002 ```compile_fail,E0081
1009 Here `X` will have already been specified the discriminant 0 by the time `Y` is
1010 encountered, so a conflict occurs.
1014 An unsupported representation was attempted on a zero-variant enum.
1016 Erroneous code example:
1018 ```compile_fail,E0084
1020 enum NightsWatch {} // error: unsupported representation for zero-variant enum
1023 It is impossible to define an integer type to be used to represent zero-variant
1024 enum values because there are no zero-variant enum values. There is no way to
1025 construct an instance of the following type using only safe code. So you have
1026 two solutions. Either you add variants in your enum:
1036 or you remove the integer represention of your enum:
1044 #### Note: this error code is no longer emitted by the compiler.
1046 Too many type arguments were supplied for a function. For example:
1048 ```compile_fail,E0107
1052 foo::<f64, bool>(); // error: wrong number of type arguments:
1053 // expected 1, found 2
1057 The number of supplied arguments must exactly match the number of defined type
1062 #### Note: this error code is no longer emitted by the compiler.
1064 You gave too many lifetime arguments. Erroneous code example:
1066 ```compile_fail,E0107
1070 f::<'static>() // error: wrong number of lifetime arguments:
1071 // expected 0, found 1
1075 Please check you give the right number of lifetime arguments. Example:
1085 It's also important to note that the Rust compiler can generally
1086 determine the lifetime by itself. Example:
1094 // it can be written like this
1095 fn get_value<'a>(&'a self) -> &'a str { &self.value }
1096 // but the compiler works fine with this too:
1097 fn without_lifetime(&self) -> &str { &self.value }
1101 let f = Foo { value: "hello".to_owned() };
1103 println!("{}", f.get_value());
1104 println!("{}", f.without_lifetime());
1110 #### Note: this error code is no longer emitted by the compiler.
1112 Too few type arguments were supplied for a function. For example:
1114 ```compile_fail,E0107
1118 foo::<f64>(); // error: wrong number of type arguments: expected 2, found 1
1122 Note that if a function takes multiple type arguments but you want the compiler
1123 to infer some of them, you can use type placeholders:
1125 ```compile_fail,E0107
1126 fn foo<T, U>(x: T) {}
1130 foo::<f64>(x); // error: wrong number of type arguments:
1131 // expected 2, found 1
1132 foo::<_, f64>(x); // same as `foo::<bool, f64>(x)`
1138 #### Note: this error code is no longer emitted by the compiler.
1140 You gave too few lifetime arguments. Example:
1142 ```compile_fail,E0107
1143 fn foo<'a: 'b, 'b: 'a>() {}
1146 foo::<'static>(); // error: wrong number of lifetime arguments:
1147 // expected 2, found 1
1151 Please check you give the right number of lifetime arguments. Example:
1154 fn foo<'a: 'b, 'b: 'a>() {}
1157 foo::<'static, 'static>();
1163 You gave an unnecessary type parameter in a type alias. Erroneous code
1166 ```compile_fail,E0091
1167 type Foo<T> = u32; // error: type parameter `T` is unused
1169 type Foo<A,B> = Box<A>; // error: type parameter `B` is unused
1172 Please check you didn't write too many type parameters. Example:
1175 type Foo = u32; // ok!
1176 type Foo2<A> = Box<A>; // ok!
1181 You tried to declare an undefined atomic operation function.
1182 Erroneous code example:
1184 ```compile_fail,E0092
1185 #![feature(intrinsics)]
1187 extern "rust-intrinsic" {
1188 fn atomic_foo(); // error: unrecognized atomic operation
1193 Please check you didn't make a mistake in the function's name. All intrinsic
1194 functions are defined in librustc_codegen_llvm/intrinsic.rs and in
1195 libcore/intrinsics.rs in the Rust source code. Example:
1198 #![feature(intrinsics)]
1200 extern "rust-intrinsic" {
1201 fn atomic_fence(); // ok!
1207 You declared an unknown intrinsic function. Erroneous code example:
1209 ```compile_fail,E0093
1210 #![feature(intrinsics)]
1212 extern "rust-intrinsic" {
1213 fn foo(); // error: unrecognized intrinsic function: `foo`
1223 Please check you didn't make a mistake in the function's name. All intrinsic
1224 functions are defined in librustc_codegen_llvm/intrinsic.rs and in
1225 libcore/intrinsics.rs in the Rust source code. Example:
1228 #![feature(intrinsics)]
1230 extern "rust-intrinsic" {
1231 fn atomic_fence(); // ok!
1243 You gave an invalid number of type parameters to an intrinsic function.
1244 Erroneous code example:
1246 ```compile_fail,E0094
1247 #![feature(intrinsics)]
1249 extern "rust-intrinsic" {
1250 fn size_of<T, U>() -> usize; // error: intrinsic has wrong number
1251 // of type parameters
1255 Please check that you provided the right number of type parameters
1256 and verify with the function declaration in the Rust source code.
1260 #![feature(intrinsics)]
1262 extern "rust-intrinsic" {
1263 fn size_of<T>() -> usize; // ok!
1269 This error means that an incorrect number of generic arguments were provided:
1271 ```compile_fail,E0107
1272 struct Foo<T> { x: T }
1274 struct Bar { x: Foo } // error: wrong number of type arguments:
1275 // expected 1, found 0
1276 struct Baz<S, T> { x: Foo<S, T> } // error: wrong number of type arguments:
1277 // expected 1, found 2
1279 fn foo<T, U>(x: T, y: U) {}
1283 foo::<bool>(x); // error: wrong number of type arguments:
1284 // expected 2, found 1
1285 foo::<bool, i32, i32>(x, 2, 4); // error: wrong number of type arguments:
1286 // expected 2, found 3
1292 f::<'static>(); // error: wrong number of lifetime arguments:
1293 // expected 0, found 1
1300 You tried to give a type parameter to a type which doesn't need it. Erroneous
1303 ```compile_fail,E0109
1304 type X = u32<i32>; // error: type parameters are not allowed on this type
1307 Please check that you used the correct type and recheck its definition. Perhaps
1308 it doesn't need the type parameter.
1313 type X = u32; // this compiles
1316 Note that type parameters for enum-variant constructors go after the variant,
1317 not after the enum (`Option::None::<u32>`, not `Option::<u32>::None`).
1321 You tried to give a lifetime parameter to a type which doesn't need it.
1322 Erroneous code example:
1324 ```compile_fail,E0110
1325 type X = u32<'static>; // error: lifetime parameters are not allowed on
1329 Please check that the correct type was used and recheck its definition; perhaps
1330 it doesn't need the lifetime parameter. Example:
1333 type X = u32; // ok!
1338 You can only define an inherent implementation for a type in the same crate
1339 where the type was defined. For example, an `impl` block as below is not allowed
1340 since `Vec` is defined in the standard library:
1342 ```compile_fail,E0116
1343 impl Vec<u8> { } // error
1346 To fix this problem, you can do either of these things:
1348 - define a trait that has the desired associated functions/types/constants and
1349 implement the trait for the type in question
1350 - define a new type wrapping the type and define an implementation on the new
1353 Note that using the `type` keyword does not work here because `type` only
1354 introduces a type alias:
1356 ```compile_fail,E0116
1357 type Bytes = Vec<u8>;
1359 impl Bytes { } // error, same as above
1364 This error indicates a violation of one of Rust's orphan rules for trait
1365 implementations. The rule prohibits any implementation of a foreign trait (a
1366 trait defined in another crate) where
1368 - the type that is implementing the trait is foreign
1369 - all of the parameters being passed to the trait (if there are any) are also
1372 Here's one example of this error:
1374 ```compile_fail,E0117
1375 impl Drop for u32 {}
1378 To avoid this kind of error, ensure that at least one local type is referenced
1382 pub struct Foo; // you define your type in your crate
1384 impl Drop for Foo { // and you can implement the trait on it!
1385 // code of trait implementation here
1386 # fn drop(&mut self) { }
1389 impl From<Foo> for i32 { // or you use a type from your crate as
1391 fn from(i: Foo) -> i32 {
1397 Alternatively, define a trait locally and implement that instead:
1401 fn get(&self) -> usize;
1405 fn get(&self) -> usize { 0 }
1409 For information on the design of the orphan rules, see [RFC 1023].
1411 [RFC 1023]: https://github.com/rust-lang/rfcs/blob/master/text/1023-rebalancing-coherence.md
1415 You're trying to write an inherent implementation for something which isn't a
1416 struct nor an enum. Erroneous code example:
1418 ```compile_fail,E0118
1419 impl (u8, u8) { // error: no base type found for inherent implementation
1420 fn get_state(&self) -> String {
1426 To fix this error, please implement a trait on the type or wrap it in a struct.
1430 // we create a trait here
1431 trait LiveLongAndProsper {
1432 fn get_state(&self) -> String;
1435 // and now you can implement it on (u8, u8)
1436 impl LiveLongAndProsper for (u8, u8) {
1437 fn get_state(&self) -> String {
1438 "He's dead, Jim!".to_owned()
1443 Alternatively, you can create a newtype. A newtype is a wrapping tuple-struct.
1444 For example, `NewType` is a newtype over `Foo` in `struct NewType(Foo)`.
1448 struct TypeWrapper((u8, u8));
1451 fn get_state(&self) -> String {
1452 "Fascinating!".to_owned()
1459 An attempt was made to implement Drop on a trait, which is not allowed: only
1460 structs and enums can implement Drop. An example causing this error:
1462 ```compile_fail,E0120
1465 impl Drop for MyTrait {
1466 fn drop(&mut self) {}
1470 A workaround for this problem is to wrap the trait up in a struct, and implement
1471 Drop on that. An example is shown below:
1475 struct MyWrapper<T: MyTrait> { foo: T }
1477 impl <T: MyTrait> Drop for MyWrapper<T> {
1478 fn drop(&mut self) {}
1483 Alternatively, wrapping trait objects requires something like the following:
1488 //or Box<MyTrait>, if you wanted an owned trait object
1489 struct MyWrapper<'a> { foo: &'a MyTrait }
1491 impl <'a> Drop for MyWrapper<'a> {
1492 fn drop(&mut self) {}
1498 In order to be consistent with Rust's lack of global type inference, type
1499 placeholders are disallowed by design in item signatures.
1501 Examples of this error include:
1503 ```compile_fail,E0121
1504 fn foo() -> _ { 5 } // error, explicitly write out the return type instead
1506 static BAR: _ = "test"; // error, explicitly write out the type instead
1511 You declared two fields of a struct with the same name. Erroneous code
1514 ```compile_fail,E0124
1517 field1: i32, // error: field is already declared
1521 Please verify that the field names have been correctly spelled. Example:
1532 It is not possible to define `main` with generic parameters.
1533 When `main` is present, it must take no arguments and return `()`.
1534 Erroneous code example:
1536 ```compile_fail,E0131
1537 fn main<T>() { // error: main function is not allowed to have generic parameters
1543 A function with the `start` attribute was declared with type parameters.
1545 Erroneous code example:
1547 ```compile_fail,E0132
1554 It is not possible to declare type parameters on a function that has the `start`
1555 attribute. Such a function must have the following type signature (for more
1556 information: http://doc.rust-lang.org/stable/book/first-edition/no-stdlib.html):
1560 fn(isize, *const *const u8) -> isize;
1569 fn my_start(argc: isize, argv: *const *const u8) -> isize {
1576 This error means that an attempt was made to match a struct type enum
1577 variant as a non-struct type:
1579 ```compile_fail,E0164
1580 enum Foo { B { i: u32 } }
1582 fn bar(foo: Foo) -> u32 {
1584 Foo::B(i) => i, // error E0164
1589 Try using `{}` instead:
1592 enum Foo { B { i: u32 } }
1594 fn bar(foo: Foo) -> u32 {
1603 Explicitly implementing both Drop and Copy for a type is currently disallowed.
1604 This feature can make some sense in theory, but the current implementation is
1605 incorrect and can lead to memory unsafety (see [issue #20126][iss20126]), so
1606 it has been disabled for now.
1608 [iss20126]: https://github.com/rust-lang/rust/issues/20126
1612 An associated function for a trait was defined to be static, but an
1613 implementation of the trait declared the same function to be a method (i.e., to
1614 take a `self` parameter).
1616 Here's an example of this error:
1618 ```compile_fail,E0185
1626 // error, method `foo` has a `&self` declaration in the impl, but not in
1634 An associated function for a trait was defined to be a method (i.e., to take a
1635 `self` parameter), but an implementation of the trait declared the same function
1638 Here's an example of this error:
1640 ```compile_fail,E0186
1648 // error, method `foo` has a `&self` declaration in the trait, but not in
1656 Trait objects need to have all associated types specified. Erroneous code
1659 ```compile_fail,E0191
1664 type Foo = Trait; // error: the value of the associated type `Bar` (from
1665 // the trait `Trait`) must be specified
1668 Please verify you specified all associated types of the trait and that you
1669 used the right trait. Example:
1676 type Foo = Trait<Bar=i32>; // ok!
1681 Negative impls are only allowed for auto traits. For more
1682 information see the [opt-in builtin traits RFC][RFC 19].
1684 [RFC 19]: https://github.com/rust-lang/rfcs/blob/master/text/0019-opt-in-builtin-traits.md
1688 #### Note: this error code is no longer emitted by the compiler.
1690 `where` clauses must use generic type parameters: it does not make sense to use
1691 them otherwise. An example causing this error:
1698 #[derive(Copy,Clone)]
1703 impl Foo for Wrapper<u32> where Wrapper<u32>: Clone {
1708 This use of a `where` clause is strange - a more common usage would look
1709 something like the following:
1716 #[derive(Copy,Clone)]
1720 impl <T> Foo for Wrapper<T> where Wrapper<T>: Clone {
1725 Here, we're saying that the implementation exists on Wrapper only when the
1726 wrapped type `T` implements `Clone`. The `where` clause is important because
1727 some types will not implement `Clone`, and thus will not get this method.
1729 In our erroneous example, however, we're referencing a single concrete type.
1730 Since we know for certain that `Wrapper<u32>` implements `Clone`, there's no
1731 reason to also specify it in a `where` clause.
1735 A type parameter was declared which shadows an existing one. An example of this
1738 ```compile_fail,E0194
1740 fn do_something(&self) -> T;
1741 fn do_something_else<T: Clone>(&self, bar: T);
1745 In this example, the trait `Foo` and the trait method `do_something_else` both
1746 define a type parameter `T`. This is not allowed: if the method wishes to
1747 define a type parameter, it must use a different name for it.
1751 Your method's lifetime parameters do not match the trait declaration.
1752 Erroneous code example:
1754 ```compile_fail,E0195
1756 fn bar<'a,'b:'a>(x: &'a str, y: &'b str);
1761 impl Trait for Foo {
1762 fn bar<'a,'b>(x: &'a str, y: &'b str) {
1763 // error: lifetime parameters or bounds on method `bar`
1764 // do not match the trait declaration
1769 The lifetime constraint `'b` for bar() implementation does not match the
1770 trait declaration. Ensure lifetime declarations match exactly in both trait
1771 declaration and implementation. Example:
1775 fn t<'a,'b:'a>(x: &'a str, y: &'b str);
1780 impl Trait for Foo {
1781 fn t<'a,'b:'a>(x: &'a str, y: &'b str) { // ok!
1788 Safe traits should not have unsafe implementations, therefore marking an
1789 implementation for a safe trait unsafe will cause a compiler error. Removing
1790 the unsafe marker on the trait noted in the error will resolve this problem.
1792 ```compile_fail,E0199
1797 // this won't compile because Bar is safe
1798 unsafe impl Bar for Foo { }
1799 // this will compile
1800 impl Bar for Foo { }
1805 Unsafe traits must have unsafe implementations. This error occurs when an
1806 implementation for an unsafe trait isn't marked as unsafe. This may be resolved
1807 by marking the unsafe implementation as unsafe.
1809 ```compile_fail,E0200
1812 unsafe trait Bar { }
1814 // this won't compile because Bar is unsafe and impl isn't unsafe
1815 impl Bar for Foo { }
1816 // this will compile
1817 unsafe impl Bar for Foo { }
1822 It is an error to define two associated items (like methods, associated types,
1823 associated functions, etc.) with the same identifier.
1827 ```compile_fail,E0201
1831 fn bar(&self) -> bool { self.0 > 5 }
1832 fn bar() {} // error: duplicate associated function
1837 fn baz(&self) -> bool;
1843 fn baz(&self) -> bool { true }
1845 // error: duplicate method
1846 fn baz(&self) -> bool { self.0 > 5 }
1848 // error: duplicate associated type
1853 Note, however, that items with the same name are allowed for inherent `impl`
1854 blocks that don't overlap:
1860 fn bar(&self) -> bool { self.0 > 5 }
1864 fn bar(&self) -> bool { self.0 }
1870 Inherent associated types were part of [RFC 195] but are not yet implemented.
1871 See [the tracking issue][iss8995] for the status of this implementation.
1873 [RFC 195]: https://github.com/rust-lang/rfcs/blob/master/text/0195-associated-items.md
1874 [iss8995]: https://github.com/rust-lang/rust/issues/8995
1878 An attempt to implement the `Copy` trait for a struct failed because one of the
1879 fields does not implement `Copy`. To fix this, you must implement `Copy` for the
1880 mentioned field. Note that this may not be possible, as in the example of
1882 ```compile_fail,E0204
1887 impl Copy for Foo { }
1890 This fails because `Vec<T>` does not implement `Copy` for any `T`.
1892 Here's another example that will fail:
1894 ```compile_fail,E0204
1901 This fails because `&mut T` is not `Copy`, even when `T` is `Copy` (this
1902 differs from the behavior for `&T`, which is always `Copy`).
1907 An attempt to implement the `Copy` trait for an enum failed because one of the
1908 variants does not implement `Copy`. To fix this, you must implement `Copy` for
1909 the mentioned variant. Note that this may not be possible, as in the example of
1911 ```compile_fail,E0205
1917 impl Copy for Foo { }
1920 This fails because `Vec<T>` does not implement `Copy` for any `T`.
1922 Here's another example that will fail:
1924 ```compile_fail,E0205
1932 This fails because `&mut T` is not `Copy`, even when `T` is `Copy` (this
1933 differs from the behavior for `&T`, which is always `Copy`).
1938 You can only implement `Copy` for a struct or enum. Both of the following
1939 examples will fail, because neither `[u8; 256]` nor `&'static mut Bar`
1940 (mutable reference to `Bar`) is a struct or enum:
1942 ```compile_fail,E0206
1943 type Foo = [u8; 256];
1944 impl Copy for Foo { } // error
1946 #[derive(Copy, Clone)]
1948 impl Copy for &'static mut Bar { } // error
1953 Any type parameter or lifetime parameter of an `impl` must meet at least one of
1954 the following criteria:
1956 - it appears in the self type of the impl
1957 - for a trait impl, it appears in the trait reference
1958 - it is bound as an associated type
1962 Suppose we have a struct `Foo` and we would like to define some methods for it.
1963 The following definition leads to a compiler error:
1965 ```compile_fail,E0207
1968 impl<T: Default> Foo {
1969 // error: the type parameter `T` is not constrained by the impl trait, self
1970 // type, or predicates [E0207]
1971 fn get(&self) -> T {
1972 <T as Default>::default()
1977 The problem is that the parameter `T` does not appear in the self type (`Foo`)
1978 of the impl. In this case, we can fix the error by moving the type parameter
1979 from the `impl` to the method `get`:
1985 // Move the type parameter from the impl to the method
1987 fn get<T: Default>(&self) -> T {
1988 <T as Default>::default()
1995 As another example, suppose we have a `Maker` trait and want to establish a
1996 type `FooMaker` that makes `Foo`s:
1998 ```compile_fail,E0207
2001 fn make(&mut self) -> Self::Item;
2010 impl<T: Default> Maker for FooMaker {
2011 // error: the type parameter `T` is not constrained by the impl trait, self
2012 // type, or predicates [E0207]
2015 fn make(&mut self) -> Foo<T> {
2016 Foo { foo: <T as Default>::default() }
2021 This fails to compile because `T` does not appear in the trait or in the
2024 One way to work around this is to introduce a phantom type parameter into
2025 `FooMaker`, like so:
2028 use std::marker::PhantomData;
2032 fn make(&mut self) -> Self::Item;
2039 // Add a type parameter to `FooMaker`
2040 struct FooMaker<T> {
2041 phantom: PhantomData<T>,
2044 impl<T: Default> Maker for FooMaker<T> {
2047 fn make(&mut self) -> Foo<T> {
2049 foo: <T as Default>::default(),
2055 Another way is to do away with the associated type in `Maker` and use an input
2056 type parameter instead:
2059 // Use a type parameter instead of an associated type here
2061 fn make(&mut self) -> Item;
2070 impl<T: Default> Maker<Foo<T>> for FooMaker {
2071 fn make(&mut self) -> Foo<T> {
2072 Foo { foo: <T as Default>::default() }
2077 ### Additional information
2079 For more information, please see [RFC 447].
2081 [RFC 447]: https://github.com/rust-lang/rfcs/blob/master/text/0447-no-unused-impl-parameters.md
2085 This error indicates a violation of one of Rust's orphan rules for trait
2086 implementations. The rule concerns the use of type parameters in an
2087 implementation of a foreign trait (a trait defined in another crate), and
2088 states that type parameters must be "covered" by a local type. To understand
2089 what this means, it is perhaps easiest to consider a few examples.
2091 If `ForeignTrait` is a trait defined in some external crate `foo`, then the
2092 following trait `impl` is an error:
2094 ```compile_fail,E0210
2095 # #[cfg(for_demonstration_only)]
2097 # #[cfg(for_demonstration_only)]
2098 use foo::ForeignTrait;
2099 # use std::panic::UnwindSafe as ForeignTrait;
2101 impl<T> ForeignTrait for T { } // error
2105 To work around this, it can be covered with a local type, `MyType`:
2108 # use std::panic::UnwindSafe as ForeignTrait;
2109 struct MyType<T>(T);
2110 impl<T> ForeignTrait for MyType<T> { } // Ok
2113 Please note that a type alias is not sufficient.
2115 For another example of an error, suppose there's another trait defined in `foo`
2116 named `ForeignTrait2` that takes two type parameters. Then this `impl` results
2117 in the same rule violation:
2119 ```ignore (cannot-doctest-multicrate-project)
2121 impl<T> ForeignTrait2<T, MyType<T>> for MyType2 { } // error
2124 The reason for this is that there are two appearances of type parameter `T` in
2125 the `impl` header, both as parameters for `ForeignTrait2`. The first appearance
2126 is uncovered, and so runs afoul of the orphan rule.
2128 Consider one more example:
2130 ```ignore (cannot-doctest-multicrate-project)
2131 impl<T> ForeignTrait2<MyType<T>, T> for MyType2 { } // Ok
2134 This only differs from the previous `impl` in that the parameters `T` and
2135 `MyType<T>` for `ForeignTrait2` have been swapped. This example does *not*
2136 violate the orphan rule; it is permitted.
2138 To see why that last example was allowed, you need to understand the general
2139 rule. Unfortunately this rule is a bit tricky to state. Consider an `impl`:
2141 ```ignore (only-for-syntax-highlight)
2142 impl<P1, ..., Pm> ForeignTrait<T1, ..., Tn> for T0 { ... }
2145 where `P1, ..., Pm` are the type parameters of the `impl` and `T0, ..., Tn`
2146 are types. One of the types `T0, ..., Tn` must be a local type (this is another
2147 orphan rule, see the explanation for E0117). Let `i` be the smallest integer
2148 such that `Ti` is a local type. Then no type parameter can appear in any of the
2151 For information on the design of the orphan rules, see [RFC 1023].
2153 [RFC 1023]: https://github.com/rust-lang/rfcs/blob/master/text/1023-rebalancing-coherence.md
2158 You used a function or type which doesn't fit the requirements for where it was
2159 used. Erroneous code examples:
2162 #![feature(intrinsics)]
2164 extern "rust-intrinsic" {
2165 fn size_of<T>(); // error: intrinsic has wrong type
2170 fn main() -> i32 { 0 }
2171 // error: main function expects type: `fn() {main}`: expected (), found i32
2178 // error: mismatched types in range: expected u8, found i8
2188 fn x(self: Rc<Foo>) {}
2189 // error: mismatched self type: expected `Foo`: expected struct
2190 // `Foo`, found struct `alloc::rc::Rc`
2194 For the first code example, please check the function definition. Example:
2197 #![feature(intrinsics)]
2199 extern "rust-intrinsic" {
2200 fn size_of<T>() -> usize; // ok!
2204 The second case example is a bit particular : the main function must always
2205 have this definition:
2211 They never take parameters and never return types.
2213 For the third example, when you match, all patterns must have the same type
2214 as the type you're matching on. Example:
2220 0u8..=3u8 => (), // ok!
2225 And finally, for the last example, only `Box<Self>`, `&Self`, `Self`,
2226 or `&mut Self` work as explicit self parameters. Example:
2232 fn x(self: Box<Foo>) {} // ok!
2239 You used an associated type which isn't defined in the trait.
2240 Erroneous code example:
2242 ```compile_fail,E0220
2247 type Foo = T1<F=i32>; // error: associated type `F` not found for `T1`
2254 // error: Baz is used but not declared
2255 fn return_bool(&self, _: &Self::Bar, _: &Self::Baz) -> bool;
2259 Make sure that you have defined the associated type in the trait body.
2260 Also, verify that you used the right trait or you didn't misspell the
2261 associated type name. Example:
2268 type Foo = T1<Bar=i32>; // ok!
2274 type Baz; // we declare `Baz` in our trait.
2276 // and now we can use it here:
2277 fn return_bool(&self, _: &Self::Bar, _: &Self::Baz) -> bool;
2283 An attempt was made to retrieve an associated type, but the type was ambiguous.
2286 ```compile_fail,E0221
2302 In this example, `Foo` defines an associated type `A`. `Bar` inherits that type
2303 from `Foo`, and defines another associated type of the same name. As a result,
2304 when we attempt to use `Self::A`, it's ambiguous whether we mean the `A` defined
2305 by `Foo` or the one defined by `Bar`.
2307 There are two options to work around this issue. The first is simply to rename
2308 one of the types. Alternatively, one can specify the intended type using the
2322 let _: <Self as Bar>::A;
2329 An attempt was made to retrieve an associated type, but the type was ambiguous.
2332 ```compile_fail,E0223
2333 trait MyTrait {type X; }
2336 let foo: MyTrait::X;
2340 The problem here is that we're attempting to take the type of X from MyTrait.
2341 Unfortunately, the type of X is not defined, because it's only made concrete in
2342 implementations of the trait. A working version of this code might look like:
2345 trait MyTrait {type X; }
2348 impl MyTrait for MyStruct {
2353 let foo: <MyStruct as MyTrait>::X;
2357 This syntax specifies that we want the X type from MyTrait, as made concrete in
2358 MyStruct. The reason that we cannot simply use `MyStruct::X` is that MyStruct
2359 might implement two different traits with identically-named associated types.
2360 This syntax allows disambiguation between the two.
2364 You attempted to use multiple types as bounds for a closure or trait object.
2365 Rust does not currently support this. A simple example that causes this error:
2367 ```compile_fail,E0225
2369 let _: Box<dyn std::io::Read + std::io::Write>;
2373 Auto traits such as Send and Sync are an exception to this rule:
2374 It's possible to have bounds of one non-builtin trait, plus any number of
2375 auto traits. For example, the following compiles correctly:
2379 let _: Box<dyn std::io::Read + Send + Sync>;
2385 An associated type binding was done outside of the type parameter declaration
2386 and `where` clause. Erroneous code example:
2388 ```compile_fail,E0229
2391 fn boo(&self) -> <Self as Foo>::A;
2396 impl Foo for isize {
2398 fn boo(&self) -> usize { 42 }
2401 fn baz<I>(x: &<I as Foo<A=Bar>>::A) {}
2402 // error: associated type bindings are not allowed here
2405 To solve this error, please move the type bindings in the type parameter
2410 # trait Foo { type A; }
2411 fn baz<I: Foo<A=Bar>>(x: &<I as Foo>::A) {} // ok!
2414 Or in the `where` clause:
2418 # trait Foo { type A; }
2419 fn baz<I>(x: &<I as Foo>::A) where I: Foo<A=Bar> {}
2424 #### Note: this error code is no longer emitted by the compiler.
2426 This error indicates that not enough type parameters were found in a type or
2429 For example, the `Foo` struct below is defined to be generic in `T`, but the
2430 type parameter is missing in the definition of `Bar`:
2432 ```compile_fail,E0107
2433 struct Foo<T> { x: T }
2435 struct Bar { x: Foo }
2440 #### Note: this error code is no longer emitted by the compiler.
2442 This error indicates that too many type parameters were found in a type or
2445 For example, the `Foo` struct below has no type parameters, but is supplied
2446 with two in the definition of `Bar`:
2448 ```compile_fail,E0107
2449 struct Foo { x: bool }
2451 struct Bar<S, T> { x: Foo<S, T> }
2456 A cross-crate opt-out trait was implemented on something which wasn't a struct
2457 or enum type. Erroneous code example:
2459 ```compile_fail,E0321
2460 #![feature(optin_builtin_traits)]
2464 impl !Sync for Foo {}
2466 unsafe impl Send for &'static Foo {}
2467 // error: cross-crate traits with a default impl, like `core::marker::Send`,
2468 // can only be implemented for a struct/enum type, not
2472 Only structs and enums are permitted to impl Send, Sync, and other opt-out
2473 trait, and the struct or enum must be local to the current crate. So, for
2474 example, `unsafe impl Send for Rc<Foo>` is not allowed.
2478 The `Sized` trait is a special trait built-in to the compiler for types with a
2479 constant size known at compile-time. This trait is automatically implemented
2480 for types as needed by the compiler, and it is currently disallowed to
2481 explicitly implement it for a type.
2485 An associated const was implemented when another trait item was expected.
2486 Erroneous code example:
2488 ```compile_fail,E0323
2497 // error: item `N` is an associated const, which doesn't match its
2498 // trait `<Bar as Foo>`
2502 Please verify that the associated const wasn't misspelled and the correct trait
2503 was implemented. Example:
2513 type N = u32; // ok!
2527 const N : u32 = 0; // ok!
2533 A method was implemented when another trait item was expected. Erroneous
2536 ```compile_fail,E0324
2547 // error: item `N` is an associated method, which doesn't match its
2548 // trait `<Bar as Foo>`
2552 To fix this error, please verify that the method name wasn't misspelled and
2553 verify that you are indeed implementing the correct trait items. Example:
2573 An associated type was implemented when another trait item was expected.
2574 Erroneous code example:
2576 ```compile_fail,E0325
2585 // error: item `N` is an associated type, which doesn't match its
2586 // trait `<Bar as Foo>`
2590 Please verify that the associated type name wasn't misspelled and your
2591 implementation corresponds to the trait definition. Example:
2601 type N = u32; // ok!
2615 const N : u32 = 0; // ok!
2621 The types of any associated constants in a trait implementation must match the
2622 types in the trait definition. This error indicates that there was a mismatch.
2624 Here's an example of this error:
2626 ```compile_fail,E0326
2634 const BAR: u32 = 5; // error, expected bool, found u32
2640 The Unsize trait should not be implemented directly. All implementations of
2641 Unsize are provided automatically by the compiler.
2643 Erroneous code example:
2645 ```compile_fail,E0328
2648 use std::marker::Unsize;
2652 impl<T> Unsize<T> for MyType {}
2655 If you are defining your own smart pointer type and would like to enable
2656 conversion from a sized to an unsized type with the
2657 [DST coercion system][RFC 982], use [`CoerceUnsized`] instead.
2660 #![feature(coerce_unsized)]
2662 use std::ops::CoerceUnsized;
2664 pub struct MyType<T: ?Sized> {
2665 field_with_unsized_type: T,
2668 impl<T, U> CoerceUnsized<MyType<U>> for MyType<T>
2669 where T: CoerceUnsized<U> {}
2672 [RFC 982]: https://github.com/rust-lang/rfcs/blob/master/text/0982-dst-coercion.md
2673 [`CoerceUnsized`]: https://doc.rust-lang.org/std/ops/trait.CoerceUnsized.html
2677 // Associated consts can now be accessed through generic type parameters, and
2678 // this error is no longer emitted.
2680 // FIXME: consider whether to leave it in the error index, or remove it entirely
2681 // as associated consts is not stabilized yet.
2684 An attempt was made to access an associated constant through either a generic
2685 type parameter or `Self`. This is not supported yet. An example causing this
2686 error is shown below:
2695 impl Foo for MyStruct {
2696 const BAR: f64 = 0f64;
2699 fn get_bar_bad<F: Foo>(t: F) -> f64 {
2704 Currently, the value of `BAR` for a particular type can only be accessed
2705 through a concrete type, as shown below:
2714 fn get_bar_good() -> f64 {
2715 <MyStruct as Foo>::BAR
2722 An attempt was made to implement `Drop` on a concrete specialization of a
2723 generic type. An example is shown below:
2725 ```compile_fail,E0366
2730 impl Drop for Foo<u32> {
2731 fn drop(&mut self) {}
2735 This code is not legal: it is not possible to specialize `Drop` to a subset of
2736 implementations of a generic type. One workaround for this is to wrap the
2737 generic type, as shown below:
2749 fn drop(&mut self) {}
2755 An attempt was made to implement `Drop` on a specialization of a generic type.
2756 An example is shown below:
2758 ```compile_fail,E0367
2761 struct MyStruct<T> {
2765 impl<T: Foo> Drop for MyStruct<T> {
2766 fn drop(&mut self) {}
2770 This code is not legal: it is not possible to specialize `Drop` to a subset of
2771 implementations of a generic type. In order for this code to work, `MyStruct`
2772 must also require that `T` implements `Foo`. Alternatively, another option is
2773 to wrap the generic type in another that specializes appropriately:
2778 struct MyStruct<T> {
2782 struct MyStructWrapper<T: Foo> {
2786 impl <T: Foo> Drop for MyStructWrapper<T> {
2787 fn drop(&mut self) {}
2793 This error indicates that a binary assignment operator like `+=` or `^=` was
2794 applied to a type that doesn't support it. For example:
2796 ```compile_fail,E0368
2797 let mut x = 12f32; // error: binary operation `<<` cannot be applied to
2803 To fix this error, please check that this type implements this binary
2807 let mut x = 12u32; // the `u32` type does implement the `ShlAssign` trait
2812 It is also possible to overload most operators for your own type by
2813 implementing the `[OP]Assign` traits from `std::ops`.
2815 Another problem you might be facing is this: suppose you've overloaded the `+`
2816 operator for some type `Foo` by implementing the `std::ops::Add` trait for
2817 `Foo`, but you find that using `+=` does not work, as in this example:
2819 ```compile_fail,E0368
2827 fn add(self, rhs: Foo) -> Foo {
2833 let mut x: Foo = Foo(5);
2834 x += Foo(7); // error, `+= cannot be applied to the type `Foo`
2838 This is because `AddAssign` is not automatically implemented, so you need to
2839 manually implement it for your type.
2843 A binary operation was attempted on a type which doesn't support it.
2844 Erroneous code example:
2846 ```compile_fail,E0369
2847 let x = 12f32; // error: binary operation `<<` cannot be applied to
2853 To fix this error, please check that this type implements this binary
2857 let x = 12u32; // the `u32` type does implement it:
2858 // https://doc.rust-lang.org/stable/std/ops/trait.Shl.html
2863 It is also possible to overload most operators for your own type by
2864 implementing traits from `std::ops`.
2866 String concatenation appends the string on the right to the string on the
2867 left and may require reallocation. This requires ownership of the string
2868 on the left. If something should be added to a string literal, move the
2869 literal to the heap by allocating it with `to_owned()` like in
2870 `"Your text".to_owned()`.
2875 The maximum value of an enum was reached, so it cannot be automatically
2876 set in the next enum value. Erroneous code example:
2879 #[deny(overflowing_literals)]
2881 X = 0x7fffffffffffffff,
2882 Y, // error: enum discriminant overflowed on value after
2883 // 9223372036854775807: i64; set explicitly via
2884 // Y = -9223372036854775808 if that is desired outcome
2888 To fix this, please set manually the next enum value or put the enum variant
2889 with the maximum value at the end of the enum. Examples:
2893 X = 0x7fffffffffffffff,
2903 X = 0x7fffffffffffffff,
2909 When `Trait2` is a subtrait of `Trait1` (for example, when `Trait2` has a
2910 definition like `trait Trait2: Trait1 { ... }`), it is not allowed to implement
2911 `Trait1` for `Trait2`. This is because `Trait2` already implements `Trait1` by
2912 definition, so it is not useful to do this.
2916 ```compile_fail,E0371
2917 trait Foo { fn foo(&self) { } }
2921 impl Bar for Baz { } // error, `Baz` implements `Bar` by definition
2922 impl Foo for Baz { } // error, `Baz` implements `Bar` which implements `Foo`
2923 impl Baz for Baz { } // error, `Baz` (trivially) implements `Baz`
2924 impl Baz for Bar { } // Note: This is OK
2929 A struct without a field containing an unsized type cannot implement
2931 [unsized type](https://doc.rust-lang.org/book/first-edition/unsized-types.html)
2932 is any type that the compiler doesn't know the length or alignment of at
2933 compile time. Any struct containing an unsized type is also unsized.
2935 Example of erroneous code:
2937 ```compile_fail,E0374
2938 #![feature(coerce_unsized)]
2939 use std::ops::CoerceUnsized;
2941 struct Foo<T: ?Sized> {
2945 // error: Struct `Foo` has no unsized fields that need `CoerceUnsized`.
2946 impl<T, U> CoerceUnsized<Foo<U>> for Foo<T>
2947 where T: CoerceUnsized<U> {}
2950 `CoerceUnsized` is used to coerce one struct containing an unsized type
2951 into another struct containing a different unsized type. If the struct
2952 doesn't have any fields of unsized types then you don't need explicit
2953 coercion to get the types you want. To fix this you can either
2954 not try to implement `CoerceUnsized` or you can add a field that is
2955 unsized to the struct.
2960 #![feature(coerce_unsized)]
2961 use std::ops::CoerceUnsized;
2963 // We don't need to impl `CoerceUnsized` here.
2968 // We add the unsized type field to the struct.
2969 struct Bar<T: ?Sized> {
2974 // The struct has an unsized field so we can implement
2975 // `CoerceUnsized` for it.
2976 impl<T, U> CoerceUnsized<Bar<U>> for Bar<T>
2977 where T: CoerceUnsized<U> {}
2980 Note that `CoerceUnsized` is mainly used by smart pointers like `Box`, `Rc`
2981 and `Arc` to be able to mark that they can coerce unsized types that they
2986 A struct with more than one field containing an unsized type cannot implement
2987 `CoerceUnsized`. This only occurs when you are trying to coerce one of the
2988 types in your struct to another type in the struct. In this case we try to
2989 impl `CoerceUnsized` from `T` to `U` which are both types that the struct
2990 takes. An [unsized type] is any type that the compiler doesn't know the length
2991 or alignment of at compile time. Any struct containing an unsized type is also
2994 Example of erroneous code:
2996 ```compile_fail,E0375
2997 #![feature(coerce_unsized)]
2998 use std::ops::CoerceUnsized;
3000 struct Foo<T: ?Sized, U: ?Sized> {
3006 // error: Struct `Foo` has more than one unsized field.
3007 impl<T, U> CoerceUnsized<Foo<U, T>> for Foo<T, U> {}
3010 `CoerceUnsized` only allows for coercion from a structure with a single
3011 unsized type field to another struct with a single unsized type field.
3012 In fact Rust only allows for a struct to have one unsized type in a struct
3013 and that unsized type must be the last field in the struct. So having two
3014 unsized types in a single struct is not allowed by the compiler. To fix this
3015 use only one field containing an unsized type in the struct and then use
3016 multiple structs to manage each unsized type field you need.
3021 #![feature(coerce_unsized)]
3022 use std::ops::CoerceUnsized;
3024 struct Foo<T: ?Sized> {
3029 impl <T, U> CoerceUnsized<Foo<U>> for Foo<T>
3030 where T: CoerceUnsized<U> {}
3032 fn coerce_foo<T: CoerceUnsized<U>, U>(t: T) -> Foo<U> {
3033 Foo { a: 12i32, b: t } // we use coercion to get the `Foo<U>` type we need
3037 [unsized type]: https://doc.rust-lang.org/book/first-edition/unsized-types.html
3041 The type you are trying to impl `CoerceUnsized` for is not a struct.
3042 `CoerceUnsized` can only be implemented for a struct. Unsized types are
3043 already able to be coerced without an implementation of `CoerceUnsized`
3044 whereas a struct containing an unsized type needs to know the unsized type
3045 field it's containing is able to be coerced. An
3046 [unsized type](https://doc.rust-lang.org/book/first-edition/unsized-types.html)
3047 is any type that the compiler doesn't know the length or alignment of at
3048 compile time. Any struct containing an unsized type is also unsized.
3050 Example of erroneous code:
3052 ```compile_fail,E0376
3053 #![feature(coerce_unsized)]
3054 use std::ops::CoerceUnsized;
3056 struct Foo<T: ?Sized> {
3060 // error: The type `U` is not a struct
3061 impl<T, U> CoerceUnsized<U> for Foo<T> {}
3064 The `CoerceUnsized` trait takes a struct type. Make sure the type you are
3065 providing to `CoerceUnsized` is a struct with only the last field containing an
3071 #![feature(coerce_unsized)]
3072 use std::ops::CoerceUnsized;
3078 // The `Foo<U>` is a struct so `CoerceUnsized` can be implemented
3079 impl<T, U> CoerceUnsized<Foo<U>> for Foo<T> where T: CoerceUnsized<U> {}
3082 Note that in Rust, structs can only contain an unsized type if the field
3083 containing the unsized type is the last and only unsized type field in the
3088 The `DispatchFromDyn` trait currently can only be implemented for
3089 builtin pointer types and structs that are newtype wrappers around them
3090 — that is, the struct must have only one field (except for`PhantomData`),
3091 and that field must itself implement `DispatchFromDyn`.
3096 #![feature(dispatch_from_dyn, unsize)]
3099 ops::DispatchFromDyn,
3102 struct Ptr<T: ?Sized>(*const T);
3104 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Ptr<U>> for Ptr<T>
3111 #![feature(dispatch_from_dyn)]
3113 ops::DispatchFromDyn,
3114 marker::PhantomData,
3119 _phantom: PhantomData<()>,
3122 impl<T, U> DispatchFromDyn<Wrapper<U>> for Wrapper<T>
3124 T: DispatchFromDyn<U>,
3128 Example of illegal `DispatchFromDyn` implementation
3129 (illegal because of extra field)
3131 ```compile-fail,E0378
3132 #![feature(dispatch_from_dyn)]
3133 use std::ops::DispatchFromDyn;
3135 struct WrapperExtraField<T> {
3140 impl<T, U> DispatchFromDyn<WrapperExtraField<U>> for WrapperExtraField<T>
3142 T: DispatchFromDyn<U>,
3148 You tried to implement methods for a primitive type. Erroneous code example:
3150 ```compile_fail,E0390
3156 // error: only a single inherent implementation marked with
3157 // `#[lang = "mut_ptr"]` is allowed for the `*mut T` primitive
3160 This isn't allowed, but using a trait to implement a method is a good solution.
3172 impl Bar for *mut Foo {
3179 This error indicates that a type or lifetime parameter has been declared
3180 but not actually used. Here is an example that demonstrates the error:
3182 ```compile_fail,E0392
3188 If the type parameter was included by mistake, this error can be fixed
3189 by simply removing the type parameter, as shown below:
3197 Alternatively, if the type parameter was intentionally inserted, it must be
3198 used. A simple fix is shown below:
3206 This error may also commonly be found when working with unsafe code. For
3207 example, when using raw pointers one may wish to specify the lifetime for
3208 which the pointed-at data is valid. An initial attempt (below) causes this
3211 ```compile_fail,E0392
3217 We want to express the constraint that Foo should not outlive `'a`, because
3218 the data pointed to by `T` is only valid for that lifetime. The problem is
3219 that there are no actual uses of `'a`. It's possible to work around this
3220 by adding a PhantomData type to the struct, using it to tell the compiler
3221 to act as if the struct contained a borrowed reference `&'a T`:
3224 use std::marker::PhantomData;
3226 struct Foo<'a, T: 'a> {
3228 phantom: PhantomData<&'a T>
3232 [PhantomData] can also be used to express information about unused type
3235 [PhantomData]: https://doc.rust-lang.org/std/marker/struct.PhantomData.html
3239 A type parameter which references `Self` in its default value was not specified.
3240 Example of erroneous code:
3242 ```compile_fail,E0393
3245 fn together_we_will_rule_the_galaxy(son: &A) {}
3246 // error: the type parameter `T` must be explicitly specified in an
3247 // object type because its default value `Self` references the
3251 A trait object is defined over a single, fully-defined trait. With a regular
3252 default parameter, this parameter can just be substituted in. However, if the
3253 default parameter is `Self`, the trait changes for each concrete type; i.e.
3254 `i32` will be expected to implement `A<i32>`, `bool` will be expected to
3255 implement `A<bool>`, etc... These types will not share an implementation of a
3256 fully-defined trait; instead they share implementations of a trait with
3257 different parameters substituted in for each implementation. This is
3258 irreconcilable with what we need to make a trait object work, and is thus
3259 disallowed. Making the trait concrete by explicitly specifying the value of the
3260 defaulted parameter will fix this issue. Fixed example:
3265 fn together_we_will_rule_the_galaxy(son: &A<i32>) {} // Ok!
3270 You implemented a trait, overriding one or more of its associated types but did
3271 not reimplement its default methods.
3273 Example of erroneous code:
3275 ```compile_fail,E0399
3276 #![feature(associated_type_defaults)]
3284 // error - the following trait items need to be reimplemented as
3285 // `Assoc` was overridden: `bar`
3290 To fix this, add an implementation for each default method from the trait:
3293 #![feature(associated_type_defaults)]
3302 fn bar(&self) {} // ok!
3308 The functional record update syntax is only allowed for structs. (Struct-like
3309 enum variants don't qualify, for example.)
3311 Erroneous code example:
3313 ```compile_fail,E0436
3314 enum PublicationFrequency {
3316 SemiMonthly { days: (u8, u8), annual_special: bool },
3319 fn one_up_competitor(competitor_frequency: PublicationFrequency)
3320 -> PublicationFrequency {
3321 match competitor_frequency {
3322 PublicationFrequency::Weekly => PublicationFrequency::SemiMonthly {
3323 days: (1, 15), annual_special: false
3325 c @ PublicationFrequency::SemiMonthly{ .. } =>
3326 PublicationFrequency::SemiMonthly {
3327 annual_special: true, ..c // error: functional record update
3328 // syntax requires a struct
3334 Rewrite the expression without functional record update syntax:
3337 enum PublicationFrequency {
3339 SemiMonthly { days: (u8, u8), annual_special: bool },
3342 fn one_up_competitor(competitor_frequency: PublicationFrequency)
3343 -> PublicationFrequency {
3344 match competitor_frequency {
3345 PublicationFrequency::Weekly => PublicationFrequency::SemiMonthly {
3346 days: (1, 15), annual_special: false
3348 PublicationFrequency::SemiMonthly{ days, .. } =>
3349 PublicationFrequency::SemiMonthly {
3350 days, annual_special: true // ok!
3358 The length of the platform-intrinsic function `simd_shuffle`
3359 wasn't specified. Erroneous code example:
3361 ```compile_fail,E0439
3362 #![feature(platform_intrinsics)]
3364 extern "platform-intrinsic" {
3365 fn simd_shuffle<A,B>(a: A, b: A, c: [u32; 8]) -> B;
3366 // error: invalid `simd_shuffle`, needs length: `simd_shuffle`
3370 The `simd_shuffle` function needs the length of the array passed as
3371 last parameter in its name. Example:
3374 #![feature(platform_intrinsics)]
3376 extern "platform-intrinsic" {
3377 fn simd_shuffle8<A,B>(a: A, b: A, c: [u32; 8]) -> B;
3383 A platform-specific intrinsic function has the wrong number of type
3384 parameters. Erroneous code example:
3386 ```compile_fail,E0440
3387 #![feature(repr_simd)]
3388 #![feature(platform_intrinsics)]
3391 struct f64x2(f64, f64);
3393 extern "platform-intrinsic" {
3394 fn x86_mm_movemask_pd<T>(x: f64x2) -> i32;
3395 // error: platform-specific intrinsic has wrong number of type
3400 Please refer to the function declaration to see if it corresponds
3401 with yours. Example:
3404 #![feature(repr_simd)]
3405 #![feature(platform_intrinsics)]
3408 struct f64x2(f64, f64);
3410 extern "platform-intrinsic" {
3411 fn x86_mm_movemask_pd(x: f64x2) -> i32;
3417 An unknown platform-specific intrinsic function was used. Erroneous
3420 ```compile_fail,E0441
3421 #![feature(repr_simd)]
3422 #![feature(platform_intrinsics)]
3425 struct i16x8(i16, i16, i16, i16, i16, i16, i16, i16);
3427 extern "platform-intrinsic" {
3428 fn x86_mm_adds_ep16(x: i16x8, y: i16x8) -> i16x8;
3429 // error: unrecognized platform-specific intrinsic function
3433 Please verify that the function name wasn't misspelled, and ensure
3434 that it is declared in the rust source code (in the file
3435 src/librustc_platform_intrinsics/x86.rs). Example:
3438 #![feature(repr_simd)]
3439 #![feature(platform_intrinsics)]
3442 struct i16x8(i16, i16, i16, i16, i16, i16, i16, i16);
3444 extern "platform-intrinsic" {
3445 fn x86_mm_adds_epi16(x: i16x8, y: i16x8) -> i16x8; // ok!
3451 Intrinsic argument(s) and/or return value have the wrong type.
3452 Erroneous code example:
3454 ```compile_fail,E0442
3455 #![feature(repr_simd)]
3456 #![feature(platform_intrinsics)]
3459 struct i8x16(i8, i8, i8, i8, i8, i8, i8, i8,
3460 i8, i8, i8, i8, i8, i8, i8, i8);
3462 struct i32x4(i32, i32, i32, i32);
3464 struct i64x2(i64, i64);
3466 extern "platform-intrinsic" {
3467 fn x86_mm_adds_epi16(x: i8x16, y: i32x4) -> i64x2;
3468 // error: intrinsic arguments/return value have wrong type
3472 To fix this error, please refer to the function declaration to give
3473 it the awaited types. Example:
3476 #![feature(repr_simd)]
3477 #![feature(platform_intrinsics)]
3480 struct i16x8(i16, i16, i16, i16, i16, i16, i16, i16);
3482 extern "platform-intrinsic" {
3483 fn x86_mm_adds_epi16(x: i16x8, y: i16x8) -> i16x8; // ok!
3489 Intrinsic argument(s) and/or return value have the wrong type.
3490 Erroneous code example:
3492 ```compile_fail,E0443
3493 #![feature(repr_simd)]
3494 #![feature(platform_intrinsics)]
3497 struct i16x8(i16, i16, i16, i16, i16, i16, i16, i16);
3499 struct i64x8(i64, i64, i64, i64, i64, i64, i64, i64);
3501 extern "platform-intrinsic" {
3502 fn x86_mm_adds_epi16(x: i16x8, y: i16x8) -> i64x8;
3503 // error: intrinsic argument/return value has wrong type
3507 To fix this error, please refer to the function declaration to give
3508 it the awaited types. Example:
3511 #![feature(repr_simd)]
3512 #![feature(platform_intrinsics)]
3515 struct i16x8(i16, i16, i16, i16, i16, i16, i16, i16);
3517 extern "platform-intrinsic" {
3518 fn x86_mm_adds_epi16(x: i16x8, y: i16x8) -> i16x8; // ok!
3524 A platform-specific intrinsic function has wrong number of arguments.
3525 Erroneous code example:
3527 ```compile_fail,E0444
3528 #![feature(repr_simd)]
3529 #![feature(platform_intrinsics)]
3532 struct f64x2(f64, f64);
3534 extern "platform-intrinsic" {
3535 fn x86_mm_movemask_pd(x: f64x2, y: f64x2, z: f64x2) -> i32;
3536 // error: platform-specific intrinsic has invalid number of arguments
3540 Please refer to the function declaration to see if it corresponds
3541 with yours. Example:
3544 #![feature(repr_simd)]
3545 #![feature(platform_intrinsics)]
3548 struct f64x2(f64, f64);
3550 extern "platform-intrinsic" {
3551 fn x86_mm_movemask_pd(x: f64x2) -> i32; // ok!
3557 The `typeof` keyword is currently reserved but unimplemented.
3558 Erroneous code example:
3560 ```compile_fail,E0516
3562 let x: typeof(92) = 92;
3566 Try using type inference instead. Example:
3576 A non-default implementation was already made on this type so it cannot be
3577 specialized further. Erroneous code example:
3579 ```compile_fail,E0520
3580 #![feature(specialization)]
3587 impl<T> SpaceLlama for T {
3588 default fn fly(&self) {}
3592 // applies to all `Clone` T and overrides the previous impl
3593 impl<T: Clone> SpaceLlama for T {
3597 // since `i32` is clone, this conflicts with the previous implementation
3598 impl SpaceLlama for i32 {
3599 default fn fly(&self) {}
3600 // error: item `fly` is provided by an `impl` that specializes
3601 // another, but the item in the parent `impl` is not marked
3602 // `default` and so it cannot be specialized.
3606 Specialization only allows you to override `default` functions in
3609 To fix this error, you need to mark all the parent implementations as default.
3613 #![feature(specialization)]
3620 impl<T> SpaceLlama for T {
3621 default fn fly(&self) {} // This is a parent implementation.
3624 // applies to all `Clone` T; overrides the previous impl
3625 impl<T: Clone> SpaceLlama for T {
3626 default fn fly(&self) {} // This is a parent implementation but was
3627 // previously not a default one, causing the error
3630 // applies to i32, overrides the previous two impls
3631 impl SpaceLlama for i32 {
3632 fn fly(&self) {} // And now that's ok!
3638 The number of elements in an array or slice pattern differed from the number of
3639 elements in the array being matched.
3641 Example of erroneous code:
3643 ```compile_fail,E0527
3644 let r = &[1, 2, 3, 4];
3646 &[a, b] => { // error: pattern requires 2 elements but array
3648 println!("a={}, b={}", a, b);
3653 Ensure that the pattern is consistent with the size of the matched
3654 array. Additional elements can be matched with `..`:
3657 #![feature(slice_patterns)]
3659 let r = &[1, 2, 3, 4];
3661 &[a, b, ..] => { // ok!
3662 println!("a={}, b={}", a, b);
3669 An array or slice pattern required more elements than were present in the
3672 Example of erroneous code:
3674 ```compile_fail,E0528
3675 #![feature(slice_patterns)]
3679 &[a, b, c, rest..] => { // error: pattern requires at least 3
3680 // elements but array has 2
3681 println!("a={}, b={}, c={} rest={:?}", a, b, c, rest);
3686 Ensure that the matched array has at least as many elements as the pattern
3687 requires. You can match an arbitrary number of remaining elements with `..`:
3690 #![feature(slice_patterns)]
3692 let r = &[1, 2, 3, 4, 5];
3694 &[a, b, c, rest..] => { // ok!
3695 // prints `a=1, b=2, c=3 rest=[4, 5]`
3696 println!("a={}, b={}, c={} rest={:?}", a, b, c, rest);
3703 An array or slice pattern was matched against some other type.
3705 Example of erroneous code:
3707 ```compile_fail,E0529
3710 [a, b] => { // error: expected an array or slice, found `f32`
3711 println!("a={}, b={}", a, b);
3716 Ensure that the pattern and the expression being matched on are of consistent
3723 println!("a={}, b={}", a, b);
3730 The `inline` attribute was malformed.
3732 Erroneous code example:
3734 ```ignore (compile_fail not working here; see Issue #43707)
3735 #[inline()] // error: expected one argument
3736 pub fn something() {}
3741 The parenthesized `inline` attribute requires the parameter to be specified:
3755 Alternatively, a paren-less version of the attribute may be used to hint the
3756 compiler about inlining opportunity:
3763 For more information about the inline attribute, read:
3764 https://doc.rust-lang.org/reference.html#inline-attributes
3768 An unknown argument was given to the `inline` attribute.
3770 Erroneous code example:
3772 ```ignore (compile_fail not working here; see Issue #43707)
3773 #[inline(unknown)] // error: invalid argument
3774 pub fn something() {}
3779 The `inline` attribute only supports two arguments:
3784 All other arguments given to the `inline` attribute will return this error.
3788 #[inline(never)] // ok!
3789 pub fn something() {}
3794 For more information about the inline attribute, https:
3795 read://doc.rust-lang.org/reference.html#inline-attributes
3799 The `export_name` attribute was malformed.
3801 Erroneous code example:
3803 ```ignore (error-emitted-at-codegen-which-cannot-be-handled-by-compile_fail)
3804 #[export_name] // error: `export_name` attribute has invalid format
3805 pub fn something() {}
3810 The `export_name` attribute expects a string in order to determine the name of
3811 the exported symbol. Example:
3814 #[export_name = "some_function"] // ok!
3815 pub fn something() {}
3822 An unknown field was specified into an enum's structure variant.
3824 Erroneous code example:
3826 ```compile_fail,E0559
3831 let s = Field::Fool { joke: 0 };
3832 // error: struct variant `Field::Fool` has no field named `joke`
3835 Verify you didn't misspell the field's name or that the field exists. Example:
3842 let s = Field::Fool { joke: 0 }; // ok!
3847 An unknown field was specified into a structure.
3849 Erroneous code example:
3851 ```compile_fail,E0560
3856 let s = Simba { mother: 1, father: 0 };
3857 // error: structure `Simba` has no field named `father`
3860 Verify you didn't misspell the field's name or that the field exists. Example:
3868 let s = Simba { mother: 1, father: 0 }; // ok!
3873 If an impl has a generic parameter with the `#[may_dangle]` attribute, then
3874 that impl must be declared as an `unsafe impl.
3876 Erroneous code example:
3878 ```compile_fail,E0569
3879 #![feature(dropck_eyepatch)]
3882 impl<#[may_dangle] X> Drop for Foo<X> {
3883 fn drop(&mut self) { }
3887 In this example, we are asserting that the destructor for `Foo` will not
3888 access any data of type `X`, and require this assertion to be true for
3889 overall safety in our program. The compiler does not currently attempt to
3890 verify this assertion; therefore we must tag this `impl` as unsafe.
3894 The requested ABI is unsupported by the current target.
3896 The rust compiler maintains for each target a blacklist of ABIs unsupported on
3897 that target. If an ABI is present in such a list this usually means that the
3898 target / ABI combination is currently unsupported by llvm.
3900 If necessary, you can circumvent this check using custom target specifications.
3904 A return statement was found outside of a function body.
3906 Erroneous code example:
3908 ```compile_fail,E0572
3909 const FOO: u32 = return 0; // error: return statement outside of function body
3914 To fix this issue, just remove the return keyword or move the expression into a
3920 fn some_fn() -> u32 {
3931 In a `fn` type, a lifetime appears only in the return type,
3932 and not in the arguments types.
3934 Erroneous code example:
3936 ```compile_fail,E0581
3938 // Here, `'a` appears only in the return type:
3939 let x: for<'a> fn() -> &'a i32;
3943 To fix this issue, either use the lifetime in the arguments, or use
3948 // Here, `'a` appears only in the return type:
3949 let x: for<'a> fn(&'a i32) -> &'a i32;
3950 let y: fn() -> &'static i32;
3954 Note: The examples above used to be (erroneously) accepted by the
3955 compiler, but this was since corrected. See [issue #33685] for more
3958 [issue #33685]: https://github.com/rust-lang/rust/issues/33685
3962 A lifetime appears only in an associated-type binding,
3963 and not in the input types to the trait.
3965 Erroneous code example:
3967 ```compile_fail,E0582
3969 // No type can satisfy this requirement, since `'a` does not
3970 // appear in any of the input types (here, `i32`):
3971 where F: for<'a> Fn(i32) -> Option<&'a i32>
3978 To fix this issue, either use the lifetime in the inputs, or use
3982 fn bar<F, G>(t: F, u: G)
3983 where F: for<'a> Fn(&'a i32) -> Option<&'a i32>,
3984 G: Fn(i32) -> Option<&'static i32>,
3991 Note: The examples above used to be (erroneously) accepted by the
3992 compiler, but this was since corrected. See [issue #33685] for more
3995 [issue #33685]: https://github.com/rust-lang/rust/issues/33685
3999 This error occurs when a method is used on a type which doesn't implement it:
4001 Erroneous code example:
4003 ```compile_fail,E0599
4007 x.chocolate(); // error: no method named `chocolate` found for type `Mouth`
4008 // in the current scope
4013 An unary operator was used on a type which doesn't implement it.
4015 Example of erroneous code:
4017 ```compile_fail,E0600
4023 !Question::Yes; // error: cannot apply unary operator `!` to type `Question`
4026 In this case, `Question` would need to implement the `std::ops::Not` trait in
4027 order to be able to use `!` on it. Let's implement it:
4037 // We implement the `Not` trait on the enum.
4038 impl Not for Question {
4041 fn not(self) -> bool {
4043 Question::Yes => false, // If the `Answer` is `Yes`, then it
4045 Question::No => true, // And here we do the opposite.
4050 assert_eq!(!Question::Yes, false);
4051 assert_eq!(!Question::No, true);
4056 An attempt to index into a type which doesn't implement the `std::ops::Index`
4057 trait was performed.
4059 Erroneous code example:
4061 ```compile_fail,E0608
4062 0u8[2]; // error: cannot index into a value of type `u8`
4065 To be able to index into a type it needs to implement the `std::ops::Index`
4069 let v: Vec<u8> = vec![0, 1, 2, 3];
4071 // The `Vec` type implements the `Index` trait so you can do:
4072 println!("{}", v[2]);
4077 A cast to `char` was attempted on a type other than `u8`.
4079 Erroneous code example:
4081 ```compile_fail,E0604
4082 0u32 as char; // error: only `u8` can be cast as `char`, not `u32`
4085 As the error message indicates, only `u8` can be cast into `char`. Example:
4088 let c = 86u8 as char; // ok!
4092 For more information about casts, take a look at The Book:
4093 https://doc.rust-lang.org/book/first-edition/casting-between-types.html
4097 An invalid cast was attempted.
4099 Erroneous code examples:
4101 ```compile_fail,E0605
4103 x as Vec<u8>; // error: non-primitive cast: `u8` as `std::vec::Vec<u8>`
4107 let v = 0 as *const u8; // So here, `v` is a `*const u8`.
4108 v as &u8; // error: non-primitive cast: `*const u8` as `&u8`
4111 Only primitive types can be cast into each other. Examples:
4117 let v = 0 as *const u8;
4118 v as *const i8; // ok!
4121 For more information about casts, take a look at The Book:
4122 https://doc.rust-lang.org/book/first-edition/casting-between-types.html
4126 An incompatible cast was attempted.
4128 Erroneous code example:
4130 ```compile_fail,E0606
4131 let x = &0u8; // Here, `x` is a `&u8`.
4132 let y: u32 = x as u32; // error: casting `&u8` as `u32` is invalid
4135 When casting, keep in mind that only primitive types can be cast into each
4140 let y: u32 = *x as u32; // We dereference it first and then cast it.
4143 For more information about casts, take a look at The Book:
4144 https://doc.rust-lang.org/book/first-edition/casting-between-types.html
4148 A cast between a thin and a fat pointer was attempted.
4150 Erroneous code example:
4152 ```compile_fail,E0607
4153 let v = 0 as *const u8;
4157 First: what are thin and fat pointers?
4159 Thin pointers are "simple" pointers: they are purely a reference to a memory
4162 Fat pointers are pointers referencing Dynamically Sized Types (also called DST).
4163 DST don't have a statically known size, therefore they can only exist behind
4164 some kind of pointers that contain additional information. Slices and trait
4165 objects are DSTs. In the case of slices, the additional information the fat
4166 pointer holds is their size.
4168 To fix this error, don't try to cast directly between thin and fat pointers.
4170 For more information about casts, take a look at The Book:
4171 https://doc.rust-lang.org/book/first-edition/casting-between-types.html
4175 Attempted to access a non-existent field in a struct.
4177 Erroneous code example:
4179 ```compile_fail,E0609
4180 struct StructWithFields {
4184 let s = StructWithFields { x: 0 };
4185 println!("{}", s.foo); // error: no field `foo` on type `StructWithFields`
4188 To fix this error, check that you didn't misspell the field's name or that the
4189 field actually exists. Example:
4192 struct StructWithFields {
4196 let s = StructWithFields { x: 0 };
4197 println!("{}", s.x); // ok!
4202 Attempted to access a field on a primitive type.
4204 Erroneous code example:
4206 ```compile_fail,E0610
4208 println!("{}", x.foo); // error: `{integer}` is a primitive type, therefore
4209 // doesn't have fields
4212 Primitive types are the most basic types available in Rust and don't have
4213 fields. To access data via named fields, struct types are used. Example:
4216 // We declare struct called `Foo` containing two fields:
4222 // We create an instance of this struct:
4223 let variable = Foo { x: 0, y: -12 };
4224 // And we can now access its fields:
4225 println!("x: {}, y: {}", variable.x, variable.y);
4228 For more information about primitives and structs, take a look at The Book:
4229 https://doc.rust-lang.org/book/first-edition/primitive-types.html
4230 https://doc.rust-lang.org/book/first-edition/structs.html
4234 Attempted to dereference a variable which cannot be dereferenced.
4236 Erroneous code example:
4238 ```compile_fail,E0614
4240 *y; // error: type `u32` cannot be dereferenced
4243 Only types implementing `std::ops::Deref` can be dereferenced (such as `&T`).
4249 // So here, `x` is a `&u32`, so we can dereference it:
4255 Attempted to access a method like a field.
4257 Erroneous code example:
4259 ```compile_fail,E0615
4268 let f = Foo { x: 0 };
4269 f.method; // error: attempted to take value of method `method` on type `Foo`
4272 If you want to use a method, add `()` after it:
4275 # struct Foo { x: u32 }
4276 # impl Foo { fn method(&self) {} }
4277 # let f = Foo { x: 0 };
4281 However, if you wanted to access a field of a struct check that the field name
4282 is spelled correctly. Example:
4285 # struct Foo { x: u32 }
4286 # impl Foo { fn method(&self) {} }
4287 # let f = Foo { x: 0 };
4288 println!("{}", f.x);
4293 Attempted to access a private field on a struct.
4295 Erroneous code example:
4297 ```compile_fail,E0616
4300 x: u32, // So `x` is private in here.
4304 pub fn new() -> Foo { Foo { x: 0 } }
4308 let f = some_module::Foo::new();
4309 println!("{}", f.x); // error: field `x` of struct `some_module::Foo` is private
4312 If you want to access this field, you have two options:
4314 1) Set the field public:
4319 pub x: u32, // `x` is now public.
4323 pub fn new() -> Foo { Foo { x: 0 } }
4327 let f = some_module::Foo::new();
4328 println!("{}", f.x); // ok!
4331 2) Add a getter function:
4336 x: u32, // So `x` is still private in here.
4340 pub fn new() -> Foo { Foo { x: 0 } }
4342 // We create the getter function here:
4343 pub fn get_x(&self) -> &u32 { &self.x }
4347 let f = some_module::Foo::new();
4348 println!("{}", f.get_x()); // ok!
4353 Attempted to pass an invalid type of variable into a variadic function.
4355 Erroneous code example:
4357 ```compile_fail,E0617
4359 fn printf(c: *const i8, ...);
4363 printf(::std::ptr::null(), 0f32);
4364 // error: can't pass an `f32` to variadic function, cast to `c_double`
4368 Certain Rust types must be cast before passing them to a variadic function,
4369 because of arcane ABI rules dictated by the C standard. To fix the error,
4370 cast the value to the type specified by the error message (which you may need
4371 to import from `std::os::raw`).
4375 Attempted to call something which isn't a function nor a method.
4377 Erroneous code examples:
4379 ```compile_fail,E0618
4384 X::Entry(); // error: expected function, found `X::Entry`
4388 x(); // error: expected function, found `i32`
4391 Only functions and methods can be called using `()`. Example:
4394 // We declare a function:
4395 fn i_am_a_function() {}
4403 #### Note: this error code is no longer emitted by the compiler.
4404 The type-checker needed to know the type of an expression, but that type had not
4407 Erroneous code example:
4413 // Here, the type of `v` is not (yet) known, so we
4414 // cannot resolve this method call:
4415 v.to_uppercase(); // error: the type of this value must be known in
4422 Type inference typically proceeds from the top of the function to the bottom,
4423 figuring out types as it goes. In some cases -- notably method calls and
4424 overloadable operators like `*` -- the type checker may not have enough
4425 information *yet* to make progress. This can be true even if the rest of the
4426 function provides enough context (because the type-checker hasn't looked that
4427 far ahead yet). In this case, type annotations can be used to help it along.
4429 To fix this error, just specify the type of the variable. Example:
4432 let mut x: Vec<String> = vec![]; // We precise the type of the vec elements.
4435 v.to_uppercase(); // Since rustc now knows the type of the vec elements,
4436 // we can use `v`'s methods.
4444 A cast to an unsized type was attempted.
4446 Erroneous code example:
4448 ```compile_fail,E0620
4449 let x = &[1_usize, 2] as [usize]; // error: cast to unsized type: `&[usize; 2]`
4453 In Rust, some types don't have a known size at compile-time. For example, in a
4454 slice type like `[u32]`, the number of elements is not known at compile-time and
4455 hence the overall size cannot be computed. As a result, such types can only be
4456 manipulated through a reference (e.g., `&T` or `&mut T`) or other pointer-type
4457 (e.g., `Box` or `Rc`). Try casting to a reference instead:
4460 let x = &[1_usize, 2] as &[usize]; // ok!
4465 An intrinsic was declared without being a function.
4467 Erroneous code example:
4469 ```compile_fail,E0622
4470 #![feature(intrinsics)]
4471 extern "rust-intrinsic" {
4472 pub static breakpoint : unsafe extern "rust-intrinsic" fn();
4473 // error: intrinsic must be a function
4476 fn main() { unsafe { breakpoint(); } }
4479 An intrinsic is a function available for use in a given programming language
4480 whose implementation is handled specially by the compiler. In order to fix this
4481 error, just declare a function.
4485 A private item was used outside of its scope.
4487 Erroneous code example:
4489 ```compile_fail,E0624
4498 let foo = inner::Foo;
4499 foo.method(); // error: method `method` is private
4502 Two possibilities are available to solve this issue:
4504 1. Only use the item in the scope it has been defined:
4514 pub fn call_method(foo: &Foo) { // We create a public function.
4515 foo.method(); // Which calls the item.
4519 let foo = inner::Foo;
4520 inner::call_method(&foo); // And since the function is public, we can call the
4521 // method through it.
4524 2. Make the item public:
4531 pub fn method(&self) {} // It's now public.
4535 let foo = inner::Foo;
4536 foo.method(); // Ok!
4541 This error indicates that the struct or enum must be matched non-exhaustively
4542 as it has been marked as `non_exhaustive`.
4544 When applied within a crate, downstream users of the crate will need to use the
4545 `_` pattern when matching enums and use the `..` pattern when matching structs.
4547 For example, in the below example, since the enum is marked as
4548 `non_exhaustive`, it is required that downstream crates match non-exhaustively
4551 ```rust,ignore (pseudo-Rust)
4552 use std::error::Error as StdError;
4554 #[non_exhaustive] pub enum Error {
4559 impl StdError for Error {
4560 fn description(&self) -> &str {
4561 // This will not error, despite being marked as non_exhaustive, as this
4562 // enum is defined within the current crate, it can be matched
4565 Message(ref s) => s,
4566 Other => "other or unknown error",
4572 An example of matching non-exhaustively on the above enum is provided below:
4574 ```rust,ignore (pseudo-Rust)
4577 // This will not error as the non_exhaustive Error enum has been matched with a
4580 Message(ref s) => ...,
4586 Similarly, for structs, match with `..` to avoid this error.
4590 This error indicates that the struct or enum cannot be instantiated from
4591 outside of the defining crate as it has been marked as `non_exhaustive` and as
4592 such more fields/variants may be added in future that could cause adverse side
4593 effects for this code.
4595 It is recommended that you look for a `new` function or equivalent in the
4596 crate's documentation.
4600 This error indicates that there is a mismatch between generic parameters and
4601 impl Trait parameters in a trait declaration versus its impl.
4603 ```compile_fail,E0643
4605 fn foo(&self, _: &impl Iterator);
4608 fn foo<U: Iterator>(&self, _: &U) { } // error method `foo` has incompatible
4609 // signature for trait
4615 It is not possible to define `main` with a where clause.
4616 Erroneous code example:
4618 ```compile_fail,E0646
4619 fn main() where i32: Copy { // error: main function is not allowed to have
4626 It is not possible to define `start` with a where clause.
4627 Erroneous code example:
4629 ```compile_fail,E0647
4633 fn start(_: isize, _: *const *const u8) -> isize where (): Copy {
4634 //^ error: start function is not allowed to have a where clause
4641 `export_name` attributes may not contain null characters (`\0`).
4643 ```compile_fail,E0648
4644 #[export_name="\0foo"] // error: `export_name` may not contain null characters
4650 This error indicates that the numeric value for the method being passed exists
4651 but the type of the numeric value or binding could not be identified.
4653 The error happens on numeric literals:
4655 ```compile_fail,E0689
4659 and on numeric bindings without an identified concrete type:
4661 ```compile_fail,E0689
4663 x.neg(); // same error as above
4666 Because of this, you must give the numeric literal or binding a type:
4671 let _ = 2.0_f32.neg();
4674 let _ = (2.0 as f32).neg();
4679 A struct with the representation hint `repr(transparent)` had zero or more than
4680 on fields that were not guaranteed to be zero-sized.
4682 Erroneous code example:
4684 ```compile_fail,E0690
4685 #[repr(transparent)]
4686 struct LengthWithUnit<U> { // error: transparent struct needs exactly one
4687 value: f32, // non-zero-sized field, but has 2
4692 Because transparent structs are represented exactly like one of their fields at
4693 run time, said field must be uniquely determined. If there is no field, or if
4694 there are multiple fields, it is not clear how the struct should be represented.
4695 Note that fields of zero-typed types (e.g., `PhantomData`) can also exist
4696 alongside the field that contains the actual data, they do not count for this
4697 error. When generic types are involved (as in the above example), an error is
4698 reported because the type parameter could be non-zero-sized.
4700 To combine `repr(transparent)` with type parameters, `PhantomData` may be
4704 use std::marker::PhantomData;
4706 #[repr(transparent)]
4707 struct LengthWithUnit<U> {
4709 unit: PhantomData<U>,
4715 A struct with the `repr(transparent)` representation hint contains a zero-sized
4716 field that requires non-trivial alignment.
4718 Erroneous code example:
4720 ```compile_fail,E0691
4721 #![feature(repr_align)]
4724 struct ForceAlign32;
4726 #[repr(transparent)]
4727 struct Wrapper(f32, ForceAlign32); // error: zero-sized field in transparent
4728 // struct has alignment larger than 1
4731 A transparent struct is supposed to be represented exactly like the piece of
4732 data it contains. Zero-sized fields with different alignment requirements
4733 potentially conflict with this property. In the example above, `Wrapper` would
4734 have to be aligned to 32 bytes even though `f32` has a smaller alignment
4737 Consider removing the over-aligned zero-sized field:
4740 #[repr(transparent)]
4741 struct Wrapper(f32);
4744 Alternatively, `PhantomData<T>` has alignment 1 for all `T`, so you can use it
4745 if you need to keep the field for some reason:
4748 #![feature(repr_align)]
4750 use std::marker::PhantomData;
4753 struct ForceAlign32;
4755 #[repr(transparent)]
4756 struct Wrapper(f32, PhantomData<ForceAlign32>);
4759 Note that empty arrays `[T; 0]` have the same alignment requirement as the
4760 element type `T`. Also note that the error is conservatively reported even when
4761 the alignment of the zero-sized type is less than or equal to the data field's
4767 A method was called on a raw pointer whose inner type wasn't completely known.
4769 For example, you may have done something like:
4772 # #![deny(warnings)]
4774 let bar = foo as *const _;
4780 Here, the type of `bar` isn't known; it could be a pointer to anything. Instead,
4781 specify a type for the pointer (preferably something that makes sense for the
4782 thing you're pointing to):
4786 let bar = foo as *const i32;
4792 Even though `is_null()` exists as a method on any raw pointer, Rust shows this
4793 error because Rust allows for `self` to have arbitrary types (behind the
4794 arbitrary_self_types feature flag).
4796 This means that someone can specify such a function:
4798 ```ignore (cannot-doctest-feature-doesnt-exist-yet)
4800 fn is_null(self: *const Self) -> bool {
4801 // do something else
4806 and now when you call `.is_null()` on a raw pointer to `Foo`, there's ambiguity.
4808 Given that we don't know what type the pointer is, and there's potential
4809 ambiguity for some types, we disallow calling methods on raw pointers when
4810 the type is unknown.
4814 A `#[marker]` trait contained an associated item.
4816 The items of marker traits cannot be overridden, so there's no need to have them
4817 when they cannot be changed per-type anyway. If you wanted them for ergonomic
4818 reasons, consider making an extension trait instead.
4822 An `impl` for a `#[marker]` trait tried to override an associated item.
4824 Because marker traits are allowed to have multiple implementations for the same
4825 type, it's not allowed to override anything in those implementations, as it
4826 would be ambiguous which override should actually be used.
4831 register_diagnostics! {
4832 // E0035, merged into E0087/E0089
4833 // E0036, merged into E0087/E0089
4839 // E0122, // bounds in type aliases are ignored, turned into proper lint
4844 // E0159, // use of trait `{}` as struct constructor
4845 // E0163, // merged into E0071
4848 // E0172, // non-trait found in a type sum, moved to resolve
4849 // E0173, // manual implementations of unboxed closure traits are experimental
4851 // E0182, // merged into E0229
4853 // E0187, // can't infer the kind of the closure
4854 // E0188, // can not cast an immutable reference to a mutable pointer
4855 // E0189, // deprecated: can only cast a boxed pointer to a boxed object
4856 // E0190, // deprecated: can only cast a &-pointer to an &-object
4857 // E0196, // cannot determine a type for this closure
4858 E0203, // type parameter has more than one relaxed default bound,
4859 // and only one is supported
4861 // E0209, // builtin traits can only be implemented on structs or enums
4862 E0212, // cannot extract an associated type from a higher-ranked trait bound
4863 // E0213, // associated types are not accepted in this context
4864 // E0215, // angle-bracket notation is not stable with `Fn`
4865 // E0216, // parenthetical notation is only stable with `Fn`
4866 // E0217, // ambiguous associated type, defined in multiple supertraits
4867 // E0218, // no associated type defined
4868 // E0219, // associated type defined in higher-ranked supertrait
4869 // E0222, // Error code E0045 (variadic function must have C or cdecl calling
4870 // convention) duplicate
4871 E0224, // at least one non-builtin train is required for an object type
4872 E0227, // ambiguous lifetime bound, explicit lifetime bound required
4873 E0228, // explicit lifetime bound required
4876 // E0235, // structure constructor specifies a structure of type but
4877 // E0236, // no lang item for range syntax
4878 // E0237, // no lang item for range syntax
4879 // E0238, // parenthesized parameters may only be used with a trait
4880 // E0239, // `next` method of `Iterator` trait has unexpected type
4884 // E0245, // not a trait
4885 // E0246, // invalid recursive type
4887 // E0248, // value used as a type, now reported earlier during resolution as E0412
4889 E0307, // invalid method `self` type
4890 // E0319, // trait impls for defaulted traits allowed just for structs/enums
4891 // E0372, // coherence not object safe
4892 E0377, // the trait `CoerceUnsized` may only be implemented for a coercion
4893 // between structures with the same definition
4894 E0533, // `{}` does not name a unit variant, unit struct or a constant
4895 // E0563, // cannot determine a type for this `impl Trait`: {} // removed in 6383de15
4896 E0564, // only named lifetimes are allowed in `impl Trait`,
4897 // but `{}` was found in the type `{}`
4898 E0587, // type has conflicting packed and align representation hints
4899 E0588, // packed type cannot transitively contain a `[repr(align)]` type
4900 E0592, // duplicate definitions with name `{}`
4901 // E0611, // merged into E0616
4902 // E0612, // merged into E0609
4903 // E0613, // Removed (merged with E0609)
4904 E0627, // yield statement outside of generator literal
4905 E0632, // cannot provide explicit type parameters when `impl Trait` is used in
4906 // argument position.
4907 E0634, // type has conflicting packed representaton hints
4908 E0640, // infer outlives requirements
4909 E0641, // cannot cast to/from a pointer with an unknown kind
4910 E0645, // trait aliases not finished
4911 E0698, // type inside generator must be known in this context
4912 E0719, // duplicate values for associated type binding