1 // ignore-tidy-filelength
3 #![allow(non_snake_case)]
5 register_long_diagnostics! {
8 A pattern used to match against an enum variant must provide a sub-pattern for
9 each field of the enum variant. This error indicates that a pattern attempted to
10 extract an incorrect number of fields from a variant.
14 Apple(String, String),
19 Here the `Apple` variant has two fields, and should be matched against like so:
23 Apple(String, String),
27 let x = Fruit::Apple(String::new(), String::new());
31 Fruit::Apple(a, b) => {},
36 Matching with the wrong number of fields has no sensible interpretation:
40 Apple(String, String),
44 let x = Fruit::Apple(String::new(), String::new());
48 Fruit::Apple(a) => {},
49 Fruit::Apple(a, b, c) => {},
53 Check how many fields the enum was declared with and ensure that your pattern
58 Each field of a struct can only be bound once in a pattern. Erroneous code
68 let x = Foo { a:1, b:2 };
70 let Foo { a: x, a: y } = x;
71 // error: field `a` bound multiple times in the pattern
75 Each occurrence of a field name binds the value of that field, so to fix this
76 error you will have to remove or alter the duplicate uses of the field name.
77 Perhaps you misspelled another field name? Example:
86 let x = Foo { a:1, b:2 };
88 let Foo { a: x, b: y } = x; // ok!
94 This error indicates that a struct pattern attempted to extract a non-existent
95 field from a struct. Struct fields are identified by the name used before the
96 colon `:` so struct patterns should resemble the declaration of the struct type
106 let thing = Thing { x: 1, y: 2 };
109 Thing { x: xfield, y: yfield } => {}
113 If you are using shorthand field patterns but want to refer to the struct field
114 by a different name, you should rename it explicitly.
118 ```compile_fail,E0026
124 let thing = Thing { x: 0, y: 0 };
139 let thing = Thing { x: 0, y: 0 };
142 Thing { x, y: z } => {}
148 This error indicates that a pattern for a struct fails to specify a sub-pattern
149 for every one of the struct's fields. Ensure that each field from the struct's
150 definition is mentioned in the pattern, or use `..` to ignore unwanted fields.
154 ```compile_fail,E0027
160 let d = Dog { name: "Rusty".to_string(), age: 8 };
162 // This is incorrect.
168 This is correct (explicit):
176 let d = Dog { name: "Rusty".to_string(), age: 8 };
179 Dog { name: ref n, age: x } => {}
182 // This is also correct (ignore unused fields).
184 Dog { age: x, .. } => {}
190 In a match expression, only numbers and characters can be matched against a
191 range. This is because the compiler checks that the range is non-empty at
192 compile-time, and is unable to evaluate arbitrary comparison functions. If you
193 want to capture values of an orderable type between two end-points, you can use
196 ```compile_fail,E0029
197 let string = "salutations !";
199 // The ordering relation for strings can't be evaluated at compile time,
200 // so this doesn't work:
202 "hello" ..= "world" => {}
206 // This is a more general version, using a guard:
208 s if s >= "hello" && s <= "world" => {}
215 This error indicates that a pointer to a trait type cannot be implicitly
216 dereferenced by a pattern. Every trait defines a type, but because the
217 size of trait implementors isn't fixed, this type has no compile-time size.
218 Therefore, all accesses to trait types must be through pointers. If you
219 encounter this error you should try to avoid dereferencing the pointer.
221 ```compile_fail,E0033
222 # trait SomeTrait { fn method_one(&self){} fn method_two(&self){} }
223 # impl<T> SomeTrait for T {}
224 let trait_obj: &SomeTrait = &"some_value";
226 // This tries to implicitly dereference to create an unsized local variable.
227 let &invalid = trait_obj;
229 // You can call methods without binding to the value being pointed at.
230 trait_obj.method_one();
231 trait_obj.method_two();
234 You can read more about trait objects in the [Trait Objects] section of the
237 [Trait Objects]: https://doc.rust-lang.org/reference/types.html#trait-objects
241 The compiler doesn't know what method to call because more than one method
242 has the same prototype. Erroneous code example:
244 ```compile_fail,E0034
255 impl Trait1 for Test { fn foo() {} }
256 impl Trait2 for Test { fn foo() {} }
259 Test::foo() // error, which foo() to call?
263 To avoid this error, you have to keep only one of them and remove the others.
264 So let's take our example and fix it:
273 impl Trait1 for Test { fn foo() {} }
276 Test::foo() // and now that's good!
280 However, a better solution would be using fully explicit naming of type and
294 impl Trait1 for Test { fn foo() {} }
295 impl Trait2 for Test { fn foo() {} }
298 <Test as Trait1>::foo()
315 impl F for X { fn m(&self) { println!("I am F"); } }
316 impl G for X { fn m(&self) { println!("I am G"); } }
321 F::m(&f); // it displays "I am F"
322 G::m(&f); // it displays "I am G"
328 It is not allowed to manually call destructors in Rust. It is also not
329 necessary to do this since `drop` is called automatically whenever a value goes
332 Here's an example of this error:
334 ```compile_fail,E0040
346 let mut x = Foo { x: -7 };
347 x.drop(); // error: explicit use of destructor method
353 You can't use type or const parameters on foreign items.
354 Example of erroneous code:
356 ```compile_fail,E0044
357 extern { fn some_func<T>(x: T); }
360 To fix this, replace the generic parameter with the specializations that you
364 extern { fn some_func_i32(x: i32); }
365 extern { fn some_func_i64(x: i64); }
370 Rust only supports variadic parameters for interoperability with C code in its
371 FFI. As such, variadic parameters can only be used with functions which are
372 using the C ABI. Examples of erroneous code:
375 #![feature(unboxed_closures)]
377 extern "rust-call" { fn foo(x: u8, ...); }
381 fn foo(x: u8, ...) {}
384 To fix such code, put them in an extern "C" block:
394 Items are missing in a trait implementation. Erroneous code example:
396 ```compile_fail,E0046
404 // error: not all trait items implemented, missing: `foo`
407 When trying to make some type implement a trait `Foo`, you must, at minimum,
408 provide implementations for all of `Foo`'s required methods (meaning the
409 methods that do not have default implementations), as well as any required
410 trait items like associated types or constants. Example:
426 This error indicates that an attempted implementation of a trait method
427 has the wrong number of type or const parameters.
429 For example, the trait below has a method `foo` with a type parameter `T`,
430 but the implementation of `foo` for the type `Bar` is missing this parameter:
432 ```compile_fail,E0049
434 fn foo<T: Default>(x: T) -> Self;
439 // error: method `foo` has 0 type parameters but its trait declaration has 1
442 fn foo(x: bool) -> Self { Bar }
448 This error indicates that an attempted implementation of a trait method
449 has the wrong number of function parameters.
451 For example, the trait below has a method `foo` with two function parameters
452 (`&self` and `u8`), but the implementation of `foo` for the type `Bar` omits
455 ```compile_fail,E0050
457 fn foo(&self, x: u8) -> bool;
462 // error: method `foo` has 1 parameter but the declaration in trait `Foo::foo`
465 fn foo(&self) -> bool { true }
471 The parameters of any trait method must match between a trait implementation
472 and the trait definition.
474 Here are a couple examples of this error:
476 ```compile_fail,E0053
485 // error, expected u16, found i16
488 // error, types differ in mutability
489 fn bar(&mut self) { }
495 It is not allowed to cast to a bool. If you are trying to cast a numeric type
496 to a bool, you can compare it with zero instead:
498 ```compile_fail,E0054
501 // Not allowed, won't compile
502 let x_is_nonzero = x as bool;
509 let x_is_nonzero = x != 0;
514 During a method call, a value is automatically dereferenced as many times as
515 needed to make the value's type match the method's receiver. The catch is that
516 the compiler will only attempt to dereference a number of times up to the
517 recursion limit (which can be set via the `recursion_limit` attribute).
519 For a somewhat artificial example:
521 ```compile_fail,E0055
522 #![recursion_limit="5"]
532 let ref_foo = &&&&&Foo;
534 // error, reached the recursion limit while auto-dereferencing `&&&&&Foo`
539 One fix may be to increase the recursion limit. Note that it is possible to
540 create an infinite recursion of dereferencing, in which case the only fix is to
541 somehow break the recursion.
545 When invoking closures or other implementations of the function traits `Fn`,
546 `FnMut` or `FnOnce` using call notation, the number of parameters passed to the
547 function must match its definition.
549 An example using a closure:
551 ```compile_fail,E0057
553 let a = f(); // invalid, too few parameters
554 let b = f(4); // this works!
555 let c = f(2, 3); // invalid, too many parameters
558 A generic function must be treated similarly:
561 fn foo<F: Fn()>(f: F) {
562 f(); // this is valid, but f(3) would not work
568 The built-in function traits are generic over a tuple of the function arguments.
569 If one uses angle-bracket notation (`Fn<(T,), Output=U>`) instead of parentheses
570 (`Fn(T) -> U`) to denote the function trait, the type parameter should be a
571 tuple. Otherwise function call notation cannot be used and the trait will not be
572 implemented by closures.
574 The most likely source of this error is using angle-bracket notation without
575 wrapping the function argument type into a tuple, for example:
577 ```compile_fail,E0059
578 #![feature(unboxed_closures)]
580 fn foo<F: Fn<i32>>(f: F) -> F::Output { f(3) }
583 It can be fixed by adjusting the trait bound like this:
586 #![feature(unboxed_closures)]
588 fn foo<F: Fn<(i32,)>>(f: F) -> F::Output { f(3) }
591 Note that `(T,)` always denotes the type of a 1-tuple containing an element of
592 type `T`. The comma is necessary for syntactic disambiguation.
596 External C functions are allowed to be variadic. However, a variadic function
597 takes a minimum number of arguments. For example, consider C's variadic `printf`
601 use std::os::raw::{c_char, c_int};
604 fn printf(_: *const c_char, ...) -> c_int;
608 Using this declaration, it must be called with at least one argument, so
609 simply calling `printf()` is invalid. But the following uses are allowed:
612 # #![feature(static_nobundle)]
613 # use std::os::raw::{c_char, c_int};
614 # #[cfg_attr(all(windows, target_env = "msvc"),
615 # link(name = "legacy_stdio_definitions", kind = "static-nobundle"))]
616 # extern "C" { fn printf(_: *const c_char, ...) -> c_int; }
619 use std::ffi::CString;
621 let fmt = CString::new("test\n").unwrap();
622 printf(fmt.as_ptr());
624 let fmt = CString::new("number = %d\n").unwrap();
625 printf(fmt.as_ptr(), 3);
627 let fmt = CString::new("%d, %d\n").unwrap();
628 printf(fmt.as_ptr(), 10, 5);
633 // ^ Note: On MSVC 2015, the `printf` function is "inlined" in the C code, and
634 // the C runtime does not contain the `printf` definition. This leads to linker
635 // error from the doc test (issue #42830).
636 // This can be fixed by linking to the static library
637 // `legacy_stdio_definitions.lib` (see https://stackoverflow.com/a/36504365/).
638 // If this compatibility library is removed in the future, consider changing
639 // `printf` in this example to another well-known variadic function.
642 The number of arguments passed to a function must match the number of arguments
643 specified in the function signature.
645 For example, a function like:
648 fn f(a: u16, b: &str) {}
651 Must always be called with exactly two arguments, e.g., `f(2, "test")`.
653 Note that Rust does not have a notion of optional function arguments or
654 variadic functions (except for its C-FFI).
658 This error indicates that during an attempt to build a struct or struct-like
659 enum variant, one of the fields was specified more than once. Erroneous code
662 ```compile_fail,E0062
670 x: 0, // error: field `x` specified more than once
675 Each field should be specified exactly one time. Example:
683 let x = Foo { x: 0 }; // ok!
689 This error indicates that during an attempt to build a struct or struct-like
690 enum variant, one of the fields was not provided. Erroneous code example:
692 ```compile_fail,E0063
699 let x = Foo { x: 0 }; // error: missing field: `y`
703 Each field should be specified exactly once. Example:
712 let x = Foo { x: 0, y: 0 }; // ok!
718 The left-hand side of a compound assignment expression must be a place
719 expression. A place expression represents a memory location and includes
720 item paths (ie, namespaced variables), dereferences, indexing expressions,
721 and field references.
723 Let's start with some erroneous code examples:
725 ```compile_fail,E0067
726 use std::collections::LinkedList;
728 // Bad: assignment to non-place expression
729 LinkedList::new() += 1;
733 fn some_func(i: &mut i32) {
734 i += 12; // Error : '+=' operation cannot be applied on a reference !
738 And now some working examples:
747 fn some_func(i: &mut i32) {
754 The compiler found a function whose body contains a `return;` statement but
755 whose return type is not `()`. An example of this is:
757 ```compile_fail,E0069
764 Since `return;` is just like `return ();`, there is a mismatch between the
765 function's return type and the value being returned.
769 The left-hand side of an assignment operator must be a place expression. A
770 place expression represents a memory location and can be a variable (with
771 optional namespacing), a dereference, an indexing expression or a field
774 More details can be found in the [Expressions] section of the Reference.
776 [Expressions]: https://doc.rust-lang.org/reference/expressions.html#places-rvalues-and-temporaries
778 Now, we can go further. Here are some erroneous code examples:
780 ```compile_fail,E0070
786 const SOME_CONST : i32 = 12;
788 fn some_other_func() {}
791 SOME_CONST = 14; // error : a constant value cannot be changed!
792 1 = 3; // error : 1 isn't a valid place!
793 some_other_func() = 4; // error : we can't assign value to a function!
794 SomeStruct.x = 12; // error : SomeStruct a structure name but it is used
799 And now let's give working examples:
806 let mut s = SomeStruct {x: 0, y: 0};
808 s.x = 3; // that's good !
812 fn some_func(x: &mut i32) {
813 *x = 12; // that's good !
819 You tried to use structure-literal syntax to create an item that is
820 not a structure or enum variant.
822 Example of erroneous code:
824 ```compile_fail,E0071
826 let t = U32 { value: 4 }; // error: expected struct, variant or union type,
827 // found builtin type `u32`
830 To fix this, ensure that the name was correctly spelled, and that
831 the correct form of initializer was used.
833 For example, the code above can be fixed to:
841 let u = Foo::FirstValue(0i32);
849 #### Note: this error code is no longer emitted by the compiler.
851 You cannot define a struct (or enum) `Foo` that requires an instance of `Foo`
852 in order to make a new `Foo` value. This is because there would be no way a
853 first instance of `Foo` could be made to initialize another instance!
855 Here's an example of a struct that has this problem:
858 struct Foo { x: Box<Foo> } // error
861 One fix is to use `Option`, like so:
864 struct Foo { x: Option<Box<Foo>> }
867 Now it's possible to create at least one instance of `Foo`: `Foo { x: None }`.
871 #### Note: this error code is no longer emitted by the compiler.
873 When using the `#[simd]` attribute on a tuple struct, the components of the
874 tuple struct must all be of a concrete, nongeneric type so the compiler can
875 reason about how to use SIMD with them. This error will occur if the types
878 This will cause an error:
881 #![feature(repr_simd)]
884 struct Bad<T>(T, T, T);
890 #![feature(repr_simd)]
893 struct Good(u32, u32, u32);
898 The `#[simd]` attribute can only be applied to non empty tuple structs, because
899 it doesn't make sense to try to use SIMD operations when there are no values to
902 This will cause an error:
904 ```compile_fail,E0075
905 #![feature(repr_simd)]
914 #![feature(repr_simd)]
922 When using the `#[simd]` attribute to automatically use SIMD operations in tuple
923 struct, the types in the struct must all be of the same type, or the compiler
924 will trigger this error.
926 This will cause an error:
928 ```compile_fail,E0076
929 #![feature(repr_simd)]
932 struct Bad(u16, u32, u32);
938 #![feature(repr_simd)]
941 struct Good(u32, u32, u32);
946 When using the `#[simd]` attribute on a tuple struct, the elements in the tuple
947 must be machine types so SIMD operations can be applied to them.
949 This will cause an error:
951 ```compile_fail,E0077
952 #![feature(repr_simd)]
961 #![feature(repr_simd)]
964 struct Good(u32, u32, u32);
969 Enum discriminants are used to differentiate enum variants stored in memory.
970 This error indicates that the same value was used for two or more variants,
971 making them impossible to tell apart.
973 ```compile_fail,E0081
991 Note that variants without a manually specified discriminant are numbered from
992 top to bottom starting from 0, so clashes can occur with seemingly unrelated
995 ```compile_fail,E0081
1002 Here `X` will have already been specified the discriminant 0 by the time `Y` is
1003 encountered, so a conflict occurs.
1007 An unsupported representation was attempted on a zero-variant enum.
1009 Erroneous code example:
1011 ```compile_fail,E0084
1013 enum NightsWatch {} // error: unsupported representation for zero-variant enum
1016 It is impossible to define an integer type to be used to represent zero-variant
1017 enum values because there are no zero-variant enum values. There is no way to
1018 construct an instance of the following type using only safe code. So you have
1019 two solutions. Either you add variants in your enum:
1029 or you remove the integer represention of your enum:
1036 // FIXME(const_generics:docs): example of inferring const parameter.
1038 #### Note: this error code is no longer emitted by the compiler.
1040 Too many type arguments were supplied for a function. For example:
1042 ```compile_fail,E0107
1046 foo::<f64, bool>(); // error: wrong number of type arguments:
1047 // expected 1, found 2
1051 The number of supplied arguments must exactly match the number of defined type
1056 #### Note: this error code is no longer emitted by the compiler.
1058 You gave too many lifetime arguments. Erroneous code example:
1060 ```compile_fail,E0107
1064 f::<'static>() // error: wrong number of lifetime arguments:
1065 // expected 0, found 1
1069 Please check you give the right number of lifetime arguments. Example:
1079 It's also important to note that the Rust compiler can generally
1080 determine the lifetime by itself. Example:
1088 // it can be written like this
1089 fn get_value<'a>(&'a self) -> &'a str { &self.value }
1090 // but the compiler works fine with this too:
1091 fn without_lifetime(&self) -> &str { &self.value }
1095 let f = Foo { value: "hello".to_owned() };
1097 println!("{}", f.get_value());
1098 println!("{}", f.without_lifetime());
1104 #### Note: this error code is no longer emitted by the compiler.
1106 Too few type arguments were supplied for a function. For example:
1108 ```compile_fail,E0107
1112 foo::<f64>(); // error: wrong number of type arguments: expected 2, found 1
1116 Note that if a function takes multiple type arguments but you want the compiler
1117 to infer some of them, you can use type placeholders:
1119 ```compile_fail,E0107
1120 fn foo<T, U>(x: T) {}
1124 foo::<f64>(x); // error: wrong number of type arguments:
1125 // expected 2, found 1
1126 foo::<_, f64>(x); // same as `foo::<bool, f64>(x)`
1132 #### Note: this error code is no longer emitted by the compiler.
1134 You gave too few lifetime arguments. Example:
1136 ```compile_fail,E0107
1137 fn foo<'a: 'b, 'b: 'a>() {}
1140 foo::<'static>(); // error: wrong number of lifetime arguments:
1141 // expected 2, found 1
1145 Please check you give the right number of lifetime arguments. Example:
1148 fn foo<'a: 'b, 'b: 'a>() {}
1151 foo::<'static, 'static>();
1157 You gave an unnecessary type or const parameter in a type alias. Erroneous
1160 ```compile_fail,E0091
1161 type Foo<T> = u32; // error: type parameter `T` is unused
1163 type Foo<A,B> = Box<A>; // error: type parameter `B` is unused
1166 Please check you didn't write too many parameters. Example:
1169 type Foo = u32; // ok!
1170 type Foo2<A> = Box<A>; // ok!
1175 You tried to declare an undefined atomic operation function.
1176 Erroneous code example:
1178 ```compile_fail,E0092
1179 #![feature(intrinsics)]
1181 extern "rust-intrinsic" {
1182 fn atomic_foo(); // error: unrecognized atomic operation
1187 Please check you didn't make a mistake in the function's name. All intrinsic
1188 functions are defined in librustc_codegen_llvm/intrinsic.rs and in
1189 libcore/intrinsics.rs in the Rust source code. Example:
1192 #![feature(intrinsics)]
1194 extern "rust-intrinsic" {
1195 fn atomic_fence(); // ok!
1201 You declared an unknown intrinsic function. Erroneous code example:
1203 ```compile_fail,E0093
1204 #![feature(intrinsics)]
1206 extern "rust-intrinsic" {
1207 fn foo(); // error: unrecognized intrinsic function: `foo`
1217 Please check you didn't make a mistake in the function's name. All intrinsic
1218 functions are defined in librustc_codegen_llvm/intrinsic.rs and in
1219 libcore/intrinsics.rs in the Rust source code. Example:
1222 #![feature(intrinsics)]
1224 extern "rust-intrinsic" {
1225 fn atomic_fence(); // ok!
1237 You gave an invalid number of type parameters to an intrinsic function.
1238 Erroneous code example:
1240 ```compile_fail,E0094
1241 #![feature(intrinsics)]
1243 extern "rust-intrinsic" {
1244 fn size_of<T, U>() -> usize; // error: intrinsic has wrong number
1245 // of type parameters
1249 Please check that you provided the right number of type parameters
1250 and verify with the function declaration in the Rust source code.
1254 #![feature(intrinsics)]
1256 extern "rust-intrinsic" {
1257 fn size_of<T>() -> usize; // ok!
1263 This error means that an incorrect number of generic arguments were provided:
1265 ```compile_fail,E0107
1266 struct Foo<T> { x: T }
1268 struct Bar { x: Foo } // error: wrong number of type arguments:
1269 // expected 1, found 0
1270 struct Baz<S, T> { x: Foo<S, T> } // error: wrong number of type arguments:
1271 // expected 1, found 2
1273 fn foo<T, U>(x: T, y: U) {}
1277 foo::<bool>(x); // error: wrong number of type arguments:
1278 // expected 2, found 1
1279 foo::<bool, i32, i32>(x, 2, 4); // error: wrong number of type arguments:
1280 // expected 2, found 3
1286 f::<'static>(); // error: wrong number of lifetime arguments:
1287 // expected 0, found 1
1294 You tried to provide a generic argument to a type which doesn't need it.
1295 Erroneous code example:
1297 ```compile_fail,E0109
1298 type X = u32<i32>; // error: type arguments are not allowed for this type
1299 type Y = bool<'static>; // error: lifetime parameters are not allowed on
1303 Check that you used the correct argument and that the definition is correct.
1308 type X = u32; // ok!
1309 type Y = bool; // ok!
1312 Note that generic arguments for enum variant constructors go after the variant,
1313 not after the enum. For example, you would write `Option::None::<u32>`,
1314 rather than `Option::<u32>::None`.
1318 #### Note: this error code is no longer emitted by the compiler.
1320 You tried to provide a lifetime to a type which doesn't need it.
1321 See `E0109` for more details.
1325 You can only define an inherent implementation for a type in the same crate
1326 where the type was defined. For example, an `impl` block as below is not allowed
1327 since `Vec` is defined in the standard library:
1329 ```compile_fail,E0116
1330 impl Vec<u8> { } // error
1333 To fix this problem, you can do either of these things:
1335 - define a trait that has the desired associated functions/types/constants and
1336 implement the trait for the type in question
1337 - define a new type wrapping the type and define an implementation on the new
1340 Note that using the `type` keyword does not work here because `type` only
1341 introduces a type alias:
1343 ```compile_fail,E0116
1344 type Bytes = Vec<u8>;
1346 impl Bytes { } // error, same as above
1351 This error indicates a violation of one of Rust's orphan rules for trait
1352 implementations. The rule prohibits any implementation of a foreign trait (a
1353 trait defined in another crate) where
1355 - the type that is implementing the trait is foreign
1356 - all of the parameters being passed to the trait (if there are any) are also
1359 Here's one example of this error:
1361 ```compile_fail,E0117
1362 impl Drop for u32 {}
1365 To avoid this kind of error, ensure that at least one local type is referenced
1369 pub struct Foo; // you define your type in your crate
1371 impl Drop for Foo { // and you can implement the trait on it!
1372 // code of trait implementation here
1373 # fn drop(&mut self) { }
1376 impl From<Foo> for i32 { // or you use a type from your crate as
1378 fn from(i: Foo) -> i32 {
1384 Alternatively, define a trait locally and implement that instead:
1388 fn get(&self) -> usize;
1392 fn get(&self) -> usize { 0 }
1396 For information on the design of the orphan rules, see [RFC 1023].
1398 [RFC 1023]: https://github.com/rust-lang/rfcs/blob/master/text/1023-rebalancing-coherence.md
1402 You're trying to write an inherent implementation for something which isn't a
1403 struct nor an enum. Erroneous code example:
1405 ```compile_fail,E0118
1406 impl (u8, u8) { // error: no base type found for inherent implementation
1407 fn get_state(&self) -> String {
1413 To fix this error, please implement a trait on the type or wrap it in a struct.
1417 // we create a trait here
1418 trait LiveLongAndProsper {
1419 fn get_state(&self) -> String;
1422 // and now you can implement it on (u8, u8)
1423 impl LiveLongAndProsper for (u8, u8) {
1424 fn get_state(&self) -> String {
1425 "He's dead, Jim!".to_owned()
1430 Alternatively, you can create a newtype. A newtype is a wrapping tuple-struct.
1431 For example, `NewType` is a newtype over `Foo` in `struct NewType(Foo)`.
1435 struct TypeWrapper((u8, u8));
1438 fn get_state(&self) -> String {
1439 "Fascinating!".to_owned()
1446 An attempt was made to implement Drop on a trait, which is not allowed: only
1447 structs and enums can implement Drop. An example causing this error:
1449 ```compile_fail,E0120
1452 impl Drop for MyTrait {
1453 fn drop(&mut self) {}
1457 A workaround for this problem is to wrap the trait up in a struct, and implement
1458 Drop on that. An example is shown below:
1462 struct MyWrapper<T: MyTrait> { foo: T }
1464 impl <T: MyTrait> Drop for MyWrapper<T> {
1465 fn drop(&mut self) {}
1470 Alternatively, wrapping trait objects requires something like the following:
1475 //or Box<MyTrait>, if you wanted an owned trait object
1476 struct MyWrapper<'a> { foo: &'a MyTrait }
1478 impl <'a> Drop for MyWrapper<'a> {
1479 fn drop(&mut self) {}
1485 In order to be consistent with Rust's lack of global type inference, type
1486 placeholders are disallowed by design in item signatures.
1488 Examples of this error include:
1490 ```compile_fail,E0121
1491 fn foo() -> _ { 5 } // error, explicitly write out the return type instead
1493 static BAR: _ = "test"; // error, explicitly write out the type instead
1498 You declared two fields of a struct with the same name. Erroneous code
1501 ```compile_fail,E0124
1504 field1: i32, // error: field is already declared
1508 Please verify that the field names have been correctly spelled. Example:
1519 It is not possible to define `main` with generic parameters.
1520 When `main` is present, it must take no arguments and return `()`.
1521 Erroneous code example:
1523 ```compile_fail,E0131
1524 fn main<T>() { // error: main function is not allowed to have generic parameters
1530 A function with the `start` attribute was declared with type parameters.
1532 Erroneous code example:
1534 ```compile_fail,E0132
1541 It is not possible to declare type parameters on a function that has the `start`
1542 attribute. Such a function must have the following type signature (for more
1543 information, view [the unstable book][1]):
1545 [1]: https://doc.rust-lang.org/unstable-book/language-features/lang-items.html#writing-an-executable-without-stdlib
1549 fn(isize, *const *const u8) -> isize;
1558 fn my_start(argc: isize, argv: *const *const u8) -> isize {
1565 This error means that an attempt was made to match a struct type enum
1566 variant as a non-struct type:
1568 ```compile_fail,E0164
1569 enum Foo { B { i: u32 } }
1571 fn bar(foo: Foo) -> u32 {
1573 Foo::B(i) => i, // error E0164
1578 Try using `{}` instead:
1581 enum Foo { B { i: u32 } }
1583 fn bar(foo: Foo) -> u32 {
1592 Explicitly implementing both Drop and Copy for a type is currently disallowed.
1593 This feature can make some sense in theory, but the current implementation is
1594 incorrect and can lead to memory unsafety (see [issue #20126][iss20126]), so
1595 it has been disabled for now.
1597 [iss20126]: https://github.com/rust-lang/rust/issues/20126
1601 An associated function for a trait was defined to be static, but an
1602 implementation of the trait declared the same function to be a method (i.e., to
1603 take a `self` parameter).
1605 Here's an example of this error:
1607 ```compile_fail,E0185
1615 // error, method `foo` has a `&self` declaration in the impl, but not in
1623 An associated function for a trait was defined to be a method (i.e., to take a
1624 `self` parameter), but an implementation of the trait declared the same function
1627 Here's an example of this error:
1629 ```compile_fail,E0186
1637 // error, method `foo` has a `&self` declaration in the trait, but not in
1645 Trait objects need to have all associated types specified. Erroneous code
1648 ```compile_fail,E0191
1653 type Foo = Trait; // error: the value of the associated type `Bar` (from
1654 // the trait `Trait`) must be specified
1657 Please verify you specified all associated types of the trait and that you
1658 used the right trait. Example:
1665 type Foo = Trait<Bar=i32>; // ok!
1670 Negative impls are only allowed for auto traits. For more
1671 information see the [opt-in builtin traits RFC][RFC 19].
1673 [RFC 19]: https://github.com/rust-lang/rfcs/blob/master/text/0019-opt-in-builtin-traits.md
1677 #### Note: this error code is no longer emitted by the compiler.
1679 `where` clauses must use generic type parameters: it does not make sense to use
1680 them otherwise. An example causing this error:
1687 #[derive(Copy,Clone)]
1692 impl Foo for Wrapper<u32> where Wrapper<u32>: Clone {
1697 This use of a `where` clause is strange - a more common usage would look
1698 something like the following:
1705 #[derive(Copy,Clone)]
1709 impl <T> Foo for Wrapper<T> where Wrapper<T>: Clone {
1714 Here, we're saying that the implementation exists on Wrapper only when the
1715 wrapped type `T` implements `Clone`. The `where` clause is important because
1716 some types will not implement `Clone`, and thus will not get this method.
1718 In our erroneous example, however, we're referencing a single concrete type.
1719 Since we know for certain that `Wrapper<u32>` implements `Clone`, there's no
1720 reason to also specify it in a `where` clause.
1724 A type parameter was declared which shadows an existing one. An example of this
1727 ```compile_fail,E0194
1729 fn do_something(&self) -> T;
1730 fn do_something_else<T: Clone>(&self, bar: T);
1734 In this example, the trait `Foo` and the trait method `do_something_else` both
1735 define a type parameter `T`. This is not allowed: if the method wishes to
1736 define a type parameter, it must use a different name for it.
1740 Your method's lifetime parameters do not match the trait declaration.
1741 Erroneous code example:
1743 ```compile_fail,E0195
1745 fn bar<'a,'b:'a>(x: &'a str, y: &'b str);
1750 impl Trait for Foo {
1751 fn bar<'a,'b>(x: &'a str, y: &'b str) {
1752 // error: lifetime parameters or bounds on method `bar`
1753 // do not match the trait declaration
1758 The lifetime constraint `'b` for bar() implementation does not match the
1759 trait declaration. Ensure lifetime declarations match exactly in both trait
1760 declaration and implementation. Example:
1764 fn t<'a,'b:'a>(x: &'a str, y: &'b str);
1769 impl Trait for Foo {
1770 fn t<'a,'b:'a>(x: &'a str, y: &'b str) { // ok!
1777 Safe traits should not have unsafe implementations, therefore marking an
1778 implementation for a safe trait unsafe will cause a compiler error. Removing
1779 the unsafe marker on the trait noted in the error will resolve this problem.
1781 ```compile_fail,E0199
1786 // this won't compile because Bar is safe
1787 unsafe impl Bar for Foo { }
1788 // this will compile
1789 impl Bar for Foo { }
1794 Unsafe traits must have unsafe implementations. This error occurs when an
1795 implementation for an unsafe trait isn't marked as unsafe. This may be resolved
1796 by marking the unsafe implementation as unsafe.
1798 ```compile_fail,E0200
1801 unsafe trait Bar { }
1803 // this won't compile because Bar is unsafe and impl isn't unsafe
1804 impl Bar for Foo { }
1805 // this will compile
1806 unsafe impl Bar for Foo { }
1811 It is an error to define two associated items (like methods, associated types,
1812 associated functions, etc.) with the same identifier.
1816 ```compile_fail,E0201
1820 fn bar(&self) -> bool { self.0 > 5 }
1821 fn bar() {} // error: duplicate associated function
1826 fn baz(&self) -> bool;
1832 fn baz(&self) -> bool { true }
1834 // error: duplicate method
1835 fn baz(&self) -> bool { self.0 > 5 }
1837 // error: duplicate associated type
1842 Note, however, that items with the same name are allowed for inherent `impl`
1843 blocks that don't overlap:
1849 fn bar(&self) -> bool { self.0 > 5 }
1853 fn bar(&self) -> bool { self.0 }
1859 Inherent associated types were part of [RFC 195] but are not yet implemented.
1860 See [the tracking issue][iss8995] for the status of this implementation.
1862 [RFC 195]: https://github.com/rust-lang/rfcs/blob/master/text/0195-associated-items.md
1863 [iss8995]: https://github.com/rust-lang/rust/issues/8995
1867 An attempt to implement the `Copy` trait for a struct failed because one of the
1868 fields does not implement `Copy`. To fix this, you must implement `Copy` for the
1869 mentioned field. Note that this may not be possible, as in the example of
1871 ```compile_fail,E0204
1876 impl Copy for Foo { }
1879 This fails because `Vec<T>` does not implement `Copy` for any `T`.
1881 Here's another example that will fail:
1883 ```compile_fail,E0204
1890 This fails because `&mut T` is not `Copy`, even when `T` is `Copy` (this
1891 differs from the behavior for `&T`, which is always `Copy`).
1896 An attempt to implement the `Copy` trait for an enum failed because one of the
1897 variants does not implement `Copy`. To fix this, you must implement `Copy` for
1898 the mentioned variant. Note that this may not be possible, as in the example of
1900 ```compile_fail,E0205
1906 impl Copy for Foo { }
1909 This fails because `Vec<T>` does not implement `Copy` for any `T`.
1911 Here's another example that will fail:
1913 ```compile_fail,E0205
1921 This fails because `&mut T` is not `Copy`, even when `T` is `Copy` (this
1922 differs from the behavior for `&T`, which is always `Copy`).
1927 You can only implement `Copy` for a struct or enum. Both of the following
1928 examples will fail, because neither `[u8; 256]` nor `&'static mut Bar`
1929 (mutable reference to `Bar`) is a struct or enum:
1931 ```compile_fail,E0206
1932 type Foo = [u8; 256];
1933 impl Copy for Foo { } // error
1935 #[derive(Copy, Clone)]
1937 impl Copy for &'static mut Bar { } // error
1942 Any type parameter or lifetime parameter of an `impl` must meet at least one of
1943 the following criteria:
1945 - it appears in the self type of the impl
1946 - for a trait impl, it appears in the trait reference
1947 - it is bound as an associated type
1951 Suppose we have a struct `Foo` and we would like to define some methods for it.
1952 The following definition leads to a compiler error:
1954 ```compile_fail,E0207
1957 impl<T: Default> Foo {
1958 // error: the type parameter `T` is not constrained by the impl trait, self
1959 // type, or predicates [E0207]
1960 fn get(&self) -> T {
1961 <T as Default>::default()
1966 The problem is that the parameter `T` does not appear in the self type (`Foo`)
1967 of the impl. In this case, we can fix the error by moving the type parameter
1968 from the `impl` to the method `get`:
1974 // Move the type parameter from the impl to the method
1976 fn get<T: Default>(&self) -> T {
1977 <T as Default>::default()
1984 As another example, suppose we have a `Maker` trait and want to establish a
1985 type `FooMaker` that makes `Foo`s:
1987 ```compile_fail,E0207
1990 fn make(&mut self) -> Self::Item;
1999 impl<T: Default> Maker for FooMaker {
2000 // error: the type parameter `T` is not constrained by the impl trait, self
2001 // type, or predicates [E0207]
2004 fn make(&mut self) -> Foo<T> {
2005 Foo { foo: <T as Default>::default() }
2010 This fails to compile because `T` does not appear in the trait or in the
2013 One way to work around this is to introduce a phantom type parameter into
2014 `FooMaker`, like so:
2017 use std::marker::PhantomData;
2021 fn make(&mut self) -> Self::Item;
2028 // Add a type parameter to `FooMaker`
2029 struct FooMaker<T> {
2030 phantom: PhantomData<T>,
2033 impl<T: Default> Maker for FooMaker<T> {
2036 fn make(&mut self) -> Foo<T> {
2038 foo: <T as Default>::default(),
2044 Another way is to do away with the associated type in `Maker` and use an input
2045 type parameter instead:
2048 // Use a type parameter instead of an associated type here
2050 fn make(&mut self) -> Item;
2059 impl<T: Default> Maker<Foo<T>> for FooMaker {
2060 fn make(&mut self) -> Foo<T> {
2061 Foo { foo: <T as Default>::default() }
2066 ### Additional information
2068 For more information, please see [RFC 447].
2070 [RFC 447]: https://github.com/rust-lang/rfcs/blob/master/text/0447-no-unused-impl-parameters.md
2074 This error indicates a violation of one of Rust's orphan rules for trait
2075 implementations. The rule concerns the use of type parameters in an
2076 implementation of a foreign trait (a trait defined in another crate), and
2077 states that type parameters must be "covered" by a local type. To understand
2078 what this means, it is perhaps easiest to consider a few examples.
2080 If `ForeignTrait` is a trait defined in some external crate `foo`, then the
2081 following trait `impl` is an error:
2083 ```compile_fail,E0210
2084 # #[cfg(for_demonstration_only)]
2086 # #[cfg(for_demonstration_only)]
2087 use foo::ForeignTrait;
2088 # use std::panic::UnwindSafe as ForeignTrait;
2090 impl<T> ForeignTrait for T { } // error
2094 To work around this, it can be covered with a local type, `MyType`:
2097 # use std::panic::UnwindSafe as ForeignTrait;
2098 struct MyType<T>(T);
2099 impl<T> ForeignTrait for MyType<T> { } // Ok
2102 Please note that a type alias is not sufficient.
2104 For another example of an error, suppose there's another trait defined in `foo`
2105 named `ForeignTrait2` that takes two type parameters. Then this `impl` results
2106 in the same rule violation:
2108 ```ignore (cannot-doctest-multicrate-project)
2110 impl<T> ForeignTrait2<T, MyType<T>> for MyType2 { } // error
2113 The reason for this is that there are two appearances of type parameter `T` in
2114 the `impl` header, both as parameters for `ForeignTrait2`. The first appearance
2115 is uncovered, and so runs afoul of the orphan rule.
2117 Consider one more example:
2119 ```ignore (cannot-doctest-multicrate-project)
2120 impl<T> ForeignTrait2<MyType<T>, T> for MyType2 { } // Ok
2123 This only differs from the previous `impl` in that the parameters `T` and
2124 `MyType<T>` for `ForeignTrait2` have been swapped. This example does *not*
2125 violate the orphan rule; it is permitted.
2127 To see why that last example was allowed, you need to understand the general
2128 rule. Unfortunately this rule is a bit tricky to state. Consider an `impl`:
2130 ```ignore (only-for-syntax-highlight)
2131 impl<P1, ..., Pm> ForeignTrait<T1, ..., Tn> for T0 { ... }
2134 where `P1, ..., Pm` are the type parameters of the `impl` and `T0, ..., Tn`
2135 are types. One of the types `T0, ..., Tn` must be a local type (this is another
2136 orphan rule, see the explanation for E0117). Let `i` be the smallest integer
2137 such that `Ti` is a local type. Then no type parameter can appear in any of the
2140 For information on the design of the orphan rules, see [RFC 1023].
2142 [RFC 1023]: https://github.com/rust-lang/rfcs/blob/master/text/1023-rebalancing-coherence.md
2147 You used a function or type which doesn't fit the requirements for where it was
2148 used. Erroneous code examples:
2151 #![feature(intrinsics)]
2153 extern "rust-intrinsic" {
2154 fn size_of<T>(); // error: intrinsic has wrong type
2159 fn main() -> i32 { 0 }
2160 // error: main function expects type: `fn() {main}`: expected (), found i32
2167 // error: mismatched types in range: expected u8, found i8
2177 fn x(self: Rc<Foo>) {}
2178 // error: mismatched self type: expected `Foo`: expected struct
2179 // `Foo`, found struct `alloc::rc::Rc`
2183 For the first code example, please check the function definition. Example:
2186 #![feature(intrinsics)]
2188 extern "rust-intrinsic" {
2189 fn size_of<T>() -> usize; // ok!
2193 The second case example is a bit particular : the main function must always
2194 have this definition:
2200 They never take parameters and never return types.
2202 For the third example, when you match, all patterns must have the same type
2203 as the type you're matching on. Example:
2209 0u8..=3u8 => (), // ok!
2214 And finally, for the last example, only `Box<Self>`, `&Self`, `Self`,
2215 or `&mut Self` work as explicit self parameters. Example:
2221 fn x(self: Box<Foo>) {} // ok!
2228 You used an associated type which isn't defined in the trait.
2229 Erroneous code example:
2231 ```compile_fail,E0220
2236 type Foo = T1<F=i32>; // error: associated type `F` not found for `T1`
2243 // error: Baz is used but not declared
2244 fn return_bool(&self, _: &Self::Bar, _: &Self::Baz) -> bool;
2248 Make sure that you have defined the associated type in the trait body.
2249 Also, verify that you used the right trait or you didn't misspell the
2250 associated type name. Example:
2257 type Foo = T1<Bar=i32>; // ok!
2263 type Baz; // we declare `Baz` in our trait.
2265 // and now we can use it here:
2266 fn return_bool(&self, _: &Self::Bar, _: &Self::Baz) -> bool;
2272 An attempt was made to retrieve an associated type, but the type was ambiguous.
2275 ```compile_fail,E0221
2291 In this example, `Foo` defines an associated type `A`. `Bar` inherits that type
2292 from `Foo`, and defines another associated type of the same name. As a result,
2293 when we attempt to use `Self::A`, it's ambiguous whether we mean the `A` defined
2294 by `Foo` or the one defined by `Bar`.
2296 There are two options to work around this issue. The first is simply to rename
2297 one of the types. Alternatively, one can specify the intended type using the
2311 let _: <Self as Bar>::A;
2318 An attempt was made to retrieve an associated type, but the type was ambiguous.
2321 ```compile_fail,E0223
2322 trait MyTrait {type X; }
2325 let foo: MyTrait::X;
2329 The problem here is that we're attempting to take the type of X from MyTrait.
2330 Unfortunately, the type of X is not defined, because it's only made concrete in
2331 implementations of the trait. A working version of this code might look like:
2334 trait MyTrait {type X; }
2337 impl MyTrait for MyStruct {
2342 let foo: <MyStruct as MyTrait>::X;
2346 This syntax specifies that we want the X type from MyTrait, as made concrete in
2347 MyStruct. The reason that we cannot simply use `MyStruct::X` is that MyStruct
2348 might implement two different traits with identically-named associated types.
2349 This syntax allows disambiguation between the two.
2353 You attempted to use multiple types as bounds for a closure or trait object.
2354 Rust does not currently support this. A simple example that causes this error:
2356 ```compile_fail,E0225
2358 let _: Box<dyn std::io::Read + std::io::Write>;
2362 Auto traits such as Send and Sync are an exception to this rule:
2363 It's possible to have bounds of one non-builtin trait, plus any number of
2364 auto traits. For example, the following compiles correctly:
2368 let _: Box<dyn std::io::Read + Send + Sync>;
2374 An associated type binding was done outside of the type parameter declaration
2375 and `where` clause. Erroneous code example:
2377 ```compile_fail,E0229
2380 fn boo(&self) -> <Self as Foo>::A;
2385 impl Foo for isize {
2387 fn boo(&self) -> usize { 42 }
2390 fn baz<I>(x: &<I as Foo<A=Bar>>::A) {}
2391 // error: associated type bindings are not allowed here
2394 To solve this error, please move the type bindings in the type parameter
2399 # trait Foo { type A; }
2400 fn baz<I: Foo<A=Bar>>(x: &<I as Foo>::A) {} // ok!
2403 Or in the `where` clause:
2407 # trait Foo { type A; }
2408 fn baz<I>(x: &<I as Foo>::A) where I: Foo<A=Bar> {}
2413 #### Note: this error code is no longer emitted by the compiler.
2415 This error indicates that not enough type parameters were found in a type or
2418 For example, the `Foo` struct below is defined to be generic in `T`, but the
2419 type parameter is missing in the definition of `Bar`:
2421 ```compile_fail,E0107
2422 struct Foo<T> { x: T }
2424 struct Bar { x: Foo }
2429 #### Note: this error code is no longer emitted by the compiler.
2431 This error indicates that too many type parameters were found in a type or
2434 For example, the `Foo` struct below has no type parameters, but is supplied
2435 with two in the definition of `Bar`:
2437 ```compile_fail,E0107
2438 struct Foo { x: bool }
2440 struct Bar<S, T> { x: Foo<S, T> }
2445 A cross-crate opt-out trait was implemented on something which wasn't a struct
2446 or enum type. Erroneous code example:
2448 ```compile_fail,E0321
2449 #![feature(optin_builtin_traits)]
2453 impl !Sync for Foo {}
2455 unsafe impl Send for &'static Foo {}
2456 // error: cross-crate traits with a default impl, like `core::marker::Send`,
2457 // can only be implemented for a struct/enum type, not
2461 Only structs and enums are permitted to impl Send, Sync, and other opt-out
2462 trait, and the struct or enum must be local to the current crate. So, for
2463 example, `unsafe impl Send for Rc<Foo>` is not allowed.
2467 The `Sized` trait is a special trait built-in to the compiler for types with a
2468 constant size known at compile-time. This trait is automatically implemented
2469 for types as needed by the compiler, and it is currently disallowed to
2470 explicitly implement it for a type.
2474 An associated const was implemented when another trait item was expected.
2475 Erroneous code example:
2477 ```compile_fail,E0323
2486 // error: item `N` is an associated const, which doesn't match its
2487 // trait `<Bar as Foo>`
2491 Please verify that the associated const wasn't misspelled and the correct trait
2492 was implemented. Example:
2502 type N = u32; // ok!
2516 const N : u32 = 0; // ok!
2522 A method was implemented when another trait item was expected. Erroneous
2525 ```compile_fail,E0324
2536 // error: item `N` is an associated method, which doesn't match its
2537 // trait `<Bar as Foo>`
2541 To fix this error, please verify that the method name wasn't misspelled and
2542 verify that you are indeed implementing the correct trait items. Example:
2562 An associated type was implemented when another trait item was expected.
2563 Erroneous code example:
2565 ```compile_fail,E0325
2574 // error: item `N` is an associated type, which doesn't match its
2575 // trait `<Bar as Foo>`
2579 Please verify that the associated type name wasn't misspelled and your
2580 implementation corresponds to the trait definition. Example:
2590 type N = u32; // ok!
2604 const N : u32 = 0; // ok!
2610 The types of any associated constants in a trait implementation must match the
2611 types in the trait definition. This error indicates that there was a mismatch.
2613 Here's an example of this error:
2615 ```compile_fail,E0326
2623 const BAR: u32 = 5; // error, expected bool, found u32
2629 The Unsize trait should not be implemented directly. All implementations of
2630 Unsize are provided automatically by the compiler.
2632 Erroneous code example:
2634 ```compile_fail,E0328
2637 use std::marker::Unsize;
2641 impl<T> Unsize<T> for MyType {}
2644 If you are defining your own smart pointer type and would like to enable
2645 conversion from a sized to an unsized type with the
2646 [DST coercion system][RFC 982], use [`CoerceUnsized`] instead.
2649 #![feature(coerce_unsized)]
2651 use std::ops::CoerceUnsized;
2653 pub struct MyType<T: ?Sized> {
2654 field_with_unsized_type: T,
2657 impl<T, U> CoerceUnsized<MyType<U>> for MyType<T>
2658 where T: CoerceUnsized<U> {}
2661 [RFC 982]: https://github.com/rust-lang/rfcs/blob/master/text/0982-dst-coercion.md
2662 [`CoerceUnsized`]: https://doc.rust-lang.org/std/ops/trait.CoerceUnsized.html
2666 // Associated consts can now be accessed through generic type parameters, and
2667 // this error is no longer emitted.
2669 // FIXME: consider whether to leave it in the error index, or remove it entirely
2670 // as associated consts is not stabilized yet.
2673 An attempt was made to access an associated constant through either a generic
2674 type parameter or `Self`. This is not supported yet. An example causing this
2675 error is shown below:
2684 impl Foo for MyStruct {
2685 const BAR: f64 = 0f64;
2688 fn get_bar_bad<F: Foo>(t: F) -> f64 {
2693 Currently, the value of `BAR` for a particular type can only be accessed
2694 through a concrete type, as shown below:
2703 fn get_bar_good() -> f64 {
2704 <MyStruct as Foo>::BAR
2711 An attempt was made to implement `Drop` on a concrete specialization of a
2712 generic type. An example is shown below:
2714 ```compile_fail,E0366
2719 impl Drop for Foo<u32> {
2720 fn drop(&mut self) {}
2724 This code is not legal: it is not possible to specialize `Drop` to a subset of
2725 implementations of a generic type. One workaround for this is to wrap the
2726 generic type, as shown below:
2738 fn drop(&mut self) {}
2744 An attempt was made to implement `Drop` on a specialization of a generic type.
2745 An example is shown below:
2747 ```compile_fail,E0367
2750 struct MyStruct<T> {
2754 impl<T: Foo> Drop for MyStruct<T> {
2755 fn drop(&mut self) {}
2759 This code is not legal: it is not possible to specialize `Drop` to a subset of
2760 implementations of a generic type. In order for this code to work, `MyStruct`
2761 must also require that `T` implements `Foo`. Alternatively, another option is
2762 to wrap the generic type in another that specializes appropriately:
2767 struct MyStruct<T> {
2771 struct MyStructWrapper<T: Foo> {
2775 impl <T: Foo> Drop for MyStructWrapper<T> {
2776 fn drop(&mut self) {}
2782 This error indicates that a binary assignment operator like `+=` or `^=` was
2783 applied to a type that doesn't support it. For example:
2785 ```compile_fail,E0368
2786 let mut x = 12f32; // error: binary operation `<<` cannot be applied to
2792 To fix this error, please check that this type implements this binary
2796 let mut x = 12u32; // the `u32` type does implement the `ShlAssign` trait
2801 It is also possible to overload most operators for your own type by
2802 implementing the `[OP]Assign` traits from `std::ops`.
2804 Another problem you might be facing is this: suppose you've overloaded the `+`
2805 operator for some type `Foo` by implementing the `std::ops::Add` trait for
2806 `Foo`, but you find that using `+=` does not work, as in this example:
2808 ```compile_fail,E0368
2816 fn add(self, rhs: Foo) -> Foo {
2822 let mut x: Foo = Foo(5);
2823 x += Foo(7); // error, `+= cannot be applied to the type `Foo`
2827 This is because `AddAssign` is not automatically implemented, so you need to
2828 manually implement it for your type.
2832 A binary operation was attempted on a type which doesn't support it.
2833 Erroneous code example:
2835 ```compile_fail,E0369
2836 let x = 12f32; // error: binary operation `<<` cannot be applied to
2842 To fix this error, please check that this type implements this binary
2846 let x = 12u32; // the `u32` type does implement it:
2847 // https://doc.rust-lang.org/stable/std/ops/trait.Shl.html
2852 It is also possible to overload most operators for your own type by
2853 implementing traits from `std::ops`.
2855 String concatenation appends the string on the right to the string on the
2856 left and may require reallocation. This requires ownership of the string
2857 on the left. If something should be added to a string literal, move the
2858 literal to the heap by allocating it with `to_owned()` like in
2859 `"Your text".to_owned()`.
2864 The maximum value of an enum was reached, so it cannot be automatically
2865 set in the next enum value. Erroneous code example:
2867 ```compile_fail,E0370
2870 X = 0x7fffffffffffffff,
2871 Y, // error: enum discriminant overflowed on value after
2872 // 9223372036854775807: i64; set explicitly via
2873 // Y = -9223372036854775808 if that is desired outcome
2877 To fix this, please set manually the next enum value or put the enum variant
2878 with the maximum value at the end of the enum. Examples:
2883 X = 0x7fffffffffffffff,
2894 X = 0x7fffffffffffffff,
2900 When `Trait2` is a subtrait of `Trait1` (for example, when `Trait2` has a
2901 definition like `trait Trait2: Trait1 { ... }`), it is not allowed to implement
2902 `Trait1` for `Trait2`. This is because `Trait2` already implements `Trait1` by
2903 definition, so it is not useful to do this.
2907 ```compile_fail,E0371
2908 trait Foo { fn foo(&self) { } }
2912 impl Bar for Baz { } // error, `Baz` implements `Bar` by definition
2913 impl Foo for Baz { } // error, `Baz` implements `Bar` which implements `Foo`
2914 impl Baz for Baz { } // error, `Baz` (trivially) implements `Baz`
2915 impl Baz for Bar { } // Note: This is OK
2920 A struct without a field containing an unsized type cannot implement
2921 `CoerceUnsized`. An [unsized type][1] is any type that the compiler
2922 doesn't know the length or alignment of at compile time. Any struct
2923 containing an unsized type is also unsized.
2925 [1]: https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait
2927 Example of erroneous code:
2929 ```compile_fail,E0374
2930 #![feature(coerce_unsized)]
2931 use std::ops::CoerceUnsized;
2933 struct Foo<T: ?Sized> {
2937 // error: Struct `Foo` has no unsized fields that need `CoerceUnsized`.
2938 impl<T, U> CoerceUnsized<Foo<U>> for Foo<T>
2939 where T: CoerceUnsized<U> {}
2942 `CoerceUnsized` is used to coerce one struct containing an unsized type
2943 into another struct containing a different unsized type. If the struct
2944 doesn't have any fields of unsized types then you don't need explicit
2945 coercion to get the types you want. To fix this you can either
2946 not try to implement `CoerceUnsized` or you can add a field that is
2947 unsized to the struct.
2952 #![feature(coerce_unsized)]
2953 use std::ops::CoerceUnsized;
2955 // We don't need to impl `CoerceUnsized` here.
2960 // We add the unsized type field to the struct.
2961 struct Bar<T: ?Sized> {
2966 // The struct has an unsized field so we can implement
2967 // `CoerceUnsized` for it.
2968 impl<T, U> CoerceUnsized<Bar<U>> for Bar<T>
2969 where T: CoerceUnsized<U> {}
2972 Note that `CoerceUnsized` is mainly used by smart pointers like `Box`, `Rc`
2973 and `Arc` to be able to mark that they can coerce unsized types that they
2978 A struct with more than one field containing an unsized type cannot implement
2979 `CoerceUnsized`. This only occurs when you are trying to coerce one of the
2980 types in your struct to another type in the struct. In this case we try to
2981 impl `CoerceUnsized` from `T` to `U` which are both types that the struct
2982 takes. An [unsized type][1] is any type that the compiler doesn't know the
2983 length or alignment of at compile time. Any struct containing an unsized type
2986 Example of erroneous code:
2988 ```compile_fail,E0375
2989 #![feature(coerce_unsized)]
2990 use std::ops::CoerceUnsized;
2992 struct Foo<T: ?Sized, U: ?Sized> {
2998 // error: Struct `Foo` has more than one unsized field.
2999 impl<T, U> CoerceUnsized<Foo<U, T>> for Foo<T, U> {}
3002 `CoerceUnsized` only allows for coercion from a structure with a single
3003 unsized type field to another struct with a single unsized type field.
3004 In fact Rust only allows for a struct to have one unsized type in a struct
3005 and that unsized type must be the last field in the struct. So having two
3006 unsized types in a single struct is not allowed by the compiler. To fix this
3007 use only one field containing an unsized type in the struct and then use
3008 multiple structs to manage each unsized type field you need.
3013 #![feature(coerce_unsized)]
3014 use std::ops::CoerceUnsized;
3016 struct Foo<T: ?Sized> {
3021 impl <T, U> CoerceUnsized<Foo<U>> for Foo<T>
3022 where T: CoerceUnsized<U> {}
3024 fn coerce_foo<T: CoerceUnsized<U>, U>(t: T) -> Foo<U> {
3025 Foo { a: 12i32, b: t } // we use coercion to get the `Foo<U>` type we need
3029 [1]: https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait
3033 The type you are trying to impl `CoerceUnsized` for is not a struct.
3034 `CoerceUnsized` can only be implemented for a struct. Unsized types are
3035 already able to be coerced without an implementation of `CoerceUnsized`
3036 whereas a struct containing an unsized type needs to know the unsized type
3037 field it's containing is able to be coerced. An [unsized type][1]
3038 is any type that the compiler doesn't know the length or alignment of at
3039 compile time. Any struct containing an unsized type is also unsized.
3041 [1]: https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait
3043 Example of erroneous code:
3045 ```compile_fail,E0376
3046 #![feature(coerce_unsized)]
3047 use std::ops::CoerceUnsized;
3049 struct Foo<T: ?Sized> {
3053 // error: The type `U` is not a struct
3054 impl<T, U> CoerceUnsized<U> for Foo<T> {}
3057 The `CoerceUnsized` trait takes a struct type. Make sure the type you are
3058 providing to `CoerceUnsized` is a struct with only the last field containing an
3064 #![feature(coerce_unsized)]
3065 use std::ops::CoerceUnsized;
3071 // The `Foo<U>` is a struct so `CoerceUnsized` can be implemented
3072 impl<T, U> CoerceUnsized<Foo<U>> for Foo<T> where T: CoerceUnsized<U> {}
3075 Note that in Rust, structs can only contain an unsized type if the field
3076 containing the unsized type is the last and only unsized type field in the
3081 The `DispatchFromDyn` trait currently can only be implemented for
3082 builtin pointer types and structs that are newtype wrappers around them
3083 — that is, the struct must have only one field (except for`PhantomData`),
3084 and that field must itself implement `DispatchFromDyn`.
3089 #![feature(dispatch_from_dyn, unsize)]
3092 ops::DispatchFromDyn,
3095 struct Ptr<T: ?Sized>(*const T);
3097 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Ptr<U>> for Ptr<T>
3104 #![feature(dispatch_from_dyn)]
3106 ops::DispatchFromDyn,
3107 marker::PhantomData,
3112 _phantom: PhantomData<()>,
3115 impl<T, U> DispatchFromDyn<Wrapper<U>> for Wrapper<T>
3117 T: DispatchFromDyn<U>,
3121 Example of illegal `DispatchFromDyn` implementation
3122 (illegal because of extra field)
3124 ```compile-fail,E0378
3125 #![feature(dispatch_from_dyn)]
3126 use std::ops::DispatchFromDyn;
3128 struct WrapperExtraField<T> {
3133 impl<T, U> DispatchFromDyn<WrapperExtraField<U>> for WrapperExtraField<T>
3135 T: DispatchFromDyn<U>,
3141 You tried to implement methods for a primitive type. Erroneous code example:
3143 ```compile_fail,E0390
3149 // error: only a single inherent implementation marked with
3150 // `#[lang = "mut_ptr"]` is allowed for the `*mut T` primitive
3153 This isn't allowed, but using a trait to implement a method is a good solution.
3165 impl Bar for *mut Foo {
3172 This error indicates that a type or lifetime parameter has been declared
3173 but not actually used. Here is an example that demonstrates the error:
3175 ```compile_fail,E0392
3181 If the type parameter was included by mistake, this error can be fixed
3182 by simply removing the type parameter, as shown below:
3190 Alternatively, if the type parameter was intentionally inserted, it must be
3191 used. A simple fix is shown below:
3199 This error may also commonly be found when working with unsafe code. For
3200 example, when using raw pointers one may wish to specify the lifetime for
3201 which the pointed-at data is valid. An initial attempt (below) causes this
3204 ```compile_fail,E0392
3210 We want to express the constraint that Foo should not outlive `'a`, because
3211 the data pointed to by `T` is only valid for that lifetime. The problem is
3212 that there are no actual uses of `'a`. It's possible to work around this
3213 by adding a PhantomData type to the struct, using it to tell the compiler
3214 to act as if the struct contained a borrowed reference `&'a T`:
3217 use std::marker::PhantomData;
3219 struct Foo<'a, T: 'a> {
3221 phantom: PhantomData<&'a T>
3225 [PhantomData] can also be used to express information about unused type
3228 [PhantomData]: https://doc.rust-lang.org/std/marker/struct.PhantomData.html
3232 A type parameter which references `Self` in its default value was not specified.
3233 Example of erroneous code:
3235 ```compile_fail,E0393
3238 fn together_we_will_rule_the_galaxy(son: &A) {}
3239 // error: the type parameter `T` must be explicitly specified in an
3240 // object type because its default value `Self` references the
3244 A trait object is defined over a single, fully-defined trait. With a regular
3245 default parameter, this parameter can just be substituted in. However, if the
3246 default parameter is `Self`, the trait changes for each concrete type; i.e.
3247 `i32` will be expected to implement `A<i32>`, `bool` will be expected to
3248 implement `A<bool>`, etc... These types will not share an implementation of a
3249 fully-defined trait; instead they share implementations of a trait with
3250 different parameters substituted in for each implementation. This is
3251 irreconcilable with what we need to make a trait object work, and is thus
3252 disallowed. Making the trait concrete by explicitly specifying the value of the
3253 defaulted parameter will fix this issue. Fixed example:
3258 fn together_we_will_rule_the_galaxy(son: &A<i32>) {} // Ok!
3263 You implemented a trait, overriding one or more of its associated types but did
3264 not reimplement its default methods.
3266 Example of erroneous code:
3268 ```compile_fail,E0399
3269 #![feature(associated_type_defaults)]
3277 // error - the following trait items need to be reimplemented as
3278 // `Assoc` was overridden: `bar`
3283 To fix this, add an implementation for each default method from the trait:
3286 #![feature(associated_type_defaults)]
3295 fn bar(&self) {} // ok!
3301 The functional record update syntax is only allowed for structs. (Struct-like
3302 enum variants don't qualify, for example.)
3304 Erroneous code example:
3306 ```compile_fail,E0436
3307 enum PublicationFrequency {
3309 SemiMonthly { days: (u8, u8), annual_special: bool },
3312 fn one_up_competitor(competitor_frequency: PublicationFrequency)
3313 -> PublicationFrequency {
3314 match competitor_frequency {
3315 PublicationFrequency::Weekly => PublicationFrequency::SemiMonthly {
3316 days: (1, 15), annual_special: false
3318 c @ PublicationFrequency::SemiMonthly{ .. } =>
3319 PublicationFrequency::SemiMonthly {
3320 annual_special: true, ..c // error: functional record update
3321 // syntax requires a struct
3327 Rewrite the expression without functional record update syntax:
3330 enum PublicationFrequency {
3332 SemiMonthly { days: (u8, u8), annual_special: bool },
3335 fn one_up_competitor(competitor_frequency: PublicationFrequency)
3336 -> PublicationFrequency {
3337 match competitor_frequency {
3338 PublicationFrequency::Weekly => PublicationFrequency::SemiMonthly {
3339 days: (1, 15), annual_special: false
3341 PublicationFrequency::SemiMonthly{ days, .. } =>
3342 PublicationFrequency::SemiMonthly {
3343 days, annual_special: true // ok!
3351 The length of the platform-intrinsic function `simd_shuffle`
3352 wasn't specified. Erroneous code example:
3354 ```compile_fail,E0439
3355 #![feature(platform_intrinsics)]
3357 extern "platform-intrinsic" {
3358 fn simd_shuffle<A,B>(a: A, b: A, c: [u32; 8]) -> B;
3359 // error: invalid `simd_shuffle`, needs length: `simd_shuffle`
3363 The `simd_shuffle` function needs the length of the array passed as
3364 last parameter in its name. Example:
3367 #![feature(platform_intrinsics)]
3369 extern "platform-intrinsic" {
3370 fn simd_shuffle8<A,B>(a: A, b: A, c: [u32; 8]) -> B;
3376 The `typeof` keyword is currently reserved but unimplemented.
3377 Erroneous code example:
3379 ```compile_fail,E0516
3381 let x: typeof(92) = 92;
3385 Try using type inference instead. Example:
3395 A non-default implementation was already made on this type so it cannot be
3396 specialized further. Erroneous code example:
3398 ```compile_fail,E0520
3399 #![feature(specialization)]
3406 impl<T> SpaceLlama for T {
3407 default fn fly(&self) {}
3411 // applies to all `Clone` T and overrides the previous impl
3412 impl<T: Clone> SpaceLlama for T {
3416 // since `i32` is clone, this conflicts with the previous implementation
3417 impl SpaceLlama for i32 {
3418 default fn fly(&self) {}
3419 // error: item `fly` is provided by an `impl` that specializes
3420 // another, but the item in the parent `impl` is not marked
3421 // `default` and so it cannot be specialized.
3425 Specialization only allows you to override `default` functions in
3428 To fix this error, you need to mark all the parent implementations as default.
3432 #![feature(specialization)]
3439 impl<T> SpaceLlama for T {
3440 default fn fly(&self) {} // This is a parent implementation.
3443 // applies to all `Clone` T; overrides the previous impl
3444 impl<T: Clone> SpaceLlama for T {
3445 default fn fly(&self) {} // This is a parent implementation but was
3446 // previously not a default one, causing the error
3449 // applies to i32, overrides the previous two impls
3450 impl SpaceLlama for i32 {
3451 fn fly(&self) {} // And now that's ok!
3457 The number of elements in an array or slice pattern differed from the number of
3458 elements in the array being matched.
3460 Example of erroneous code:
3462 ```compile_fail,E0527
3463 let r = &[1, 2, 3, 4];
3465 &[a, b] => { // error: pattern requires 2 elements but array
3467 println!("a={}, b={}", a, b);
3472 Ensure that the pattern is consistent with the size of the matched
3473 array. Additional elements can be matched with `..`:
3476 #![feature(slice_patterns)]
3478 let r = &[1, 2, 3, 4];
3480 &[a, b, ..] => { // ok!
3481 println!("a={}, b={}", a, b);
3488 An array or slice pattern required more elements than were present in the
3491 Example of erroneous code:
3493 ```compile_fail,E0528
3494 #![feature(slice_patterns)]
3498 &[a, b, c, rest..] => { // error: pattern requires at least 3
3499 // elements but array has 2
3500 println!("a={}, b={}, c={} rest={:?}", a, b, c, rest);
3505 Ensure that the matched array has at least as many elements as the pattern
3506 requires. You can match an arbitrary number of remaining elements with `..`:
3509 #![feature(slice_patterns)]
3511 let r = &[1, 2, 3, 4, 5];
3513 &[a, b, c, rest..] => { // ok!
3514 // prints `a=1, b=2, c=3 rest=[4, 5]`
3515 println!("a={}, b={}, c={} rest={:?}", a, b, c, rest);
3522 An array or slice pattern was matched against some other type.
3524 Example of erroneous code:
3526 ```compile_fail,E0529
3529 [a, b] => { // error: expected an array or slice, found `f32`
3530 println!("a={}, b={}", a, b);
3535 Ensure that the pattern and the expression being matched on are of consistent
3542 println!("a={}, b={}", a, b);
3549 The `inline` attribute was malformed.
3551 Erroneous code example:
3553 ```ignore (compile_fail not working here; see Issue #43707)
3554 #[inline()] // error: expected one argument
3555 pub fn something() {}
3560 The parenthesized `inline` attribute requires the parameter to be specified:
3574 Alternatively, a paren-less version of the attribute may be used to hint the
3575 compiler about inlining opportunity:
3582 For more information about the inline attribute, read:
3583 https://doc.rust-lang.org/reference.html#inline-attributes
3587 An unknown argument was given to the `inline` attribute.
3589 Erroneous code example:
3591 ```ignore (compile_fail not working here; see Issue #43707)
3592 #[inline(unknown)] // error: invalid argument
3593 pub fn something() {}
3598 The `inline` attribute only supports two arguments:
3603 All other arguments given to the `inline` attribute will return this error.
3607 #[inline(never)] // ok!
3608 pub fn something() {}
3613 For more information about the inline attribute, https:
3614 read://doc.rust-lang.org/reference.html#inline-attributes
3618 An unknown field was specified into an enum's structure variant.
3620 Erroneous code example:
3622 ```compile_fail,E0559
3627 let s = Field::Fool { joke: 0 };
3628 // error: struct variant `Field::Fool` has no field named `joke`
3631 Verify you didn't misspell the field's name or that the field exists. Example:
3638 let s = Field::Fool { joke: 0 }; // ok!
3643 An unknown field was specified into a structure.
3645 Erroneous code example:
3647 ```compile_fail,E0560
3652 let s = Simba { mother: 1, father: 0 };
3653 // error: structure `Simba` has no field named `father`
3656 Verify you didn't misspell the field's name or that the field exists. Example:
3664 let s = Simba { mother: 1, father: 0 }; // ok!
3669 If an impl has a generic parameter with the `#[may_dangle]` attribute, then
3670 that impl must be declared as an `unsafe impl.
3672 Erroneous code example:
3674 ```compile_fail,E0569
3675 #![feature(dropck_eyepatch)]
3678 impl<#[may_dangle] X> Drop for Foo<X> {
3679 fn drop(&mut self) { }
3683 In this example, we are asserting that the destructor for `Foo` will not
3684 access any data of type `X`, and require this assertion to be true for
3685 overall safety in our program. The compiler does not currently attempt to
3686 verify this assertion; therefore we must tag this `impl` as unsafe.
3690 The requested ABI is unsupported by the current target.
3692 The rust compiler maintains for each target a blacklist of ABIs unsupported on
3693 that target. If an ABI is present in such a list this usually means that the
3694 target / ABI combination is currently unsupported by llvm.
3696 If necessary, you can circumvent this check using custom target specifications.
3700 A return statement was found outside of a function body.
3702 Erroneous code example:
3704 ```compile_fail,E0572
3705 const FOO: u32 = return 0; // error: return statement outside of function body
3710 To fix this issue, just remove the return keyword or move the expression into a
3716 fn some_fn() -> u32 {
3727 In a `fn` type, a lifetime appears only in the return type,
3728 and not in the arguments types.
3730 Erroneous code example:
3732 ```compile_fail,E0581
3734 // Here, `'a` appears only in the return type:
3735 let x: for<'a> fn() -> &'a i32;
3739 To fix this issue, either use the lifetime in the arguments, or use
3744 // Here, `'a` appears only in the return type:
3745 let x: for<'a> fn(&'a i32) -> &'a i32;
3746 let y: fn() -> &'static i32;
3750 Note: The examples above used to be (erroneously) accepted by the
3751 compiler, but this was since corrected. See [issue #33685] for more
3754 [issue #33685]: https://github.com/rust-lang/rust/issues/33685
3758 A lifetime appears only in an associated-type binding,
3759 and not in the input types to the trait.
3761 Erroneous code example:
3763 ```compile_fail,E0582
3765 // No type can satisfy this requirement, since `'a` does not
3766 // appear in any of the input types (here, `i32`):
3767 where F: for<'a> Fn(i32) -> Option<&'a i32>
3774 To fix this issue, either use the lifetime in the inputs, or use
3778 fn bar<F, G>(t: F, u: G)
3779 where F: for<'a> Fn(&'a i32) -> Option<&'a i32>,
3780 G: Fn(i32) -> Option<&'static i32>,
3787 Note: The examples above used to be (erroneously) accepted by the
3788 compiler, but this was since corrected. See [issue #33685] for more
3791 [issue #33685]: https://github.com/rust-lang/rust/issues/33685
3795 This error occurs when a method is used on a type which doesn't implement it:
3797 Erroneous code example:
3799 ```compile_fail,E0599
3803 x.chocolate(); // error: no method named `chocolate` found for type `Mouth`
3804 // in the current scope
3809 An unary operator was used on a type which doesn't implement it.
3811 Example of erroneous code:
3813 ```compile_fail,E0600
3819 !Question::Yes; // error: cannot apply unary operator `!` to type `Question`
3822 In this case, `Question` would need to implement the `std::ops::Not` trait in
3823 order to be able to use `!` on it. Let's implement it:
3833 // We implement the `Not` trait on the enum.
3834 impl Not for Question {
3837 fn not(self) -> bool {
3839 Question::Yes => false, // If the `Answer` is `Yes`, then it
3841 Question::No => true, // And here we do the opposite.
3846 assert_eq!(!Question::Yes, false);
3847 assert_eq!(!Question::No, true);
3852 An attempt to index into a type which doesn't implement the `std::ops::Index`
3853 trait was performed.
3855 Erroneous code example:
3857 ```compile_fail,E0608
3858 0u8[2]; // error: cannot index into a value of type `u8`
3861 To be able to index into a type it needs to implement the `std::ops::Index`
3865 let v: Vec<u8> = vec![0, 1, 2, 3];
3867 // The `Vec` type implements the `Index` trait so you can do:
3868 println!("{}", v[2]);
3873 A cast to `char` was attempted on a type other than `u8`.
3875 Erroneous code example:
3877 ```compile_fail,E0604
3878 0u32 as char; // error: only `u8` can be cast as `char`, not `u32`
3881 As the error message indicates, only `u8` can be cast into `char`. Example:
3884 let c = 86u8 as char; // ok!
3888 For more information about casts, take a look at the Type cast section in
3889 [The Reference Book][1].
3891 [1]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
3895 An invalid cast was attempted.
3897 Erroneous code examples:
3899 ```compile_fail,E0605
3901 x as Vec<u8>; // error: non-primitive cast: `u8` as `std::vec::Vec<u8>`
3905 let v = 0 as *const u8; // So here, `v` is a `*const u8`.
3906 v as &u8; // error: non-primitive cast: `*const u8` as `&u8`
3909 Only primitive types can be cast into each other. Examples:
3915 let v = 0 as *const u8;
3916 v as *const i8; // ok!
3919 For more information about casts, take a look at the Type cast section in
3920 [The Reference Book][1].
3922 [1]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
3926 An incompatible cast was attempted.
3928 Erroneous code example:
3930 ```compile_fail,E0606
3931 let x = &0u8; // Here, `x` is a `&u8`.
3932 let y: u32 = x as u32; // error: casting `&u8` as `u32` is invalid
3935 When casting, keep in mind that only primitive types can be cast into each
3940 let y: u32 = *x as u32; // We dereference it first and then cast it.
3943 For more information about casts, take a look at the Type cast section in
3944 [The Reference Book][1].
3946 [1]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
3950 A cast between a thin and a fat pointer was attempted.
3952 Erroneous code example:
3954 ```compile_fail,E0607
3955 let v = 0 as *const u8;
3959 First: what are thin and fat pointers?
3961 Thin pointers are "simple" pointers: they are purely a reference to a memory
3964 Fat pointers are pointers referencing Dynamically Sized Types (also called DST).
3965 DST don't have a statically known size, therefore they can only exist behind
3966 some kind of pointers that contain additional information. Slices and trait
3967 objects are DSTs. In the case of slices, the additional information the fat
3968 pointer holds is their size.
3970 To fix this error, don't try to cast directly between thin and fat pointers.
3972 For more information about casts, take a look at the Type cast section in
3973 [The Reference Book][1].
3975 [1]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
3979 Attempted to access a non-existent field in a struct.
3981 Erroneous code example:
3983 ```compile_fail,E0609
3984 struct StructWithFields {
3988 let s = StructWithFields { x: 0 };
3989 println!("{}", s.foo); // error: no field `foo` on type `StructWithFields`
3992 To fix this error, check that you didn't misspell the field's name or that the
3993 field actually exists. Example:
3996 struct StructWithFields {
4000 let s = StructWithFields { x: 0 };
4001 println!("{}", s.x); // ok!
4006 Attempted to access a field on a primitive type.
4008 Erroneous code example:
4010 ```compile_fail,E0610
4012 println!("{}", x.foo); // error: `{integer}` is a primitive type, therefore
4013 // doesn't have fields
4016 Primitive types are the most basic types available in Rust and don't have
4017 fields. To access data via named fields, struct types are used. Example:
4020 // We declare struct called `Foo` containing two fields:
4026 // We create an instance of this struct:
4027 let variable = Foo { x: 0, y: -12 };
4028 // And we can now access its fields:
4029 println!("x: {}, y: {}", variable.x, variable.y);
4032 For more information about primitives and structs, take a look at The Book:
4033 https://doc.rust-lang.org/book/ch03-02-data-types.html
4034 https://doc.rust-lang.org/book/ch05-00-structs.html
4038 Attempted to dereference a variable which cannot be dereferenced.
4040 Erroneous code example:
4042 ```compile_fail,E0614
4044 *y; // error: type `u32` cannot be dereferenced
4047 Only types implementing `std::ops::Deref` can be dereferenced (such as `&T`).
4053 // So here, `x` is a `&u32`, so we can dereference it:
4059 Attempted to access a method like a field.
4061 Erroneous code example:
4063 ```compile_fail,E0615
4072 let f = Foo { x: 0 };
4073 f.method; // error: attempted to take value of method `method` on type `Foo`
4076 If you want to use a method, add `()` after it:
4079 # struct Foo { x: u32 }
4080 # impl Foo { fn method(&self) {} }
4081 # let f = Foo { x: 0 };
4085 However, if you wanted to access a field of a struct check that the field name
4086 is spelled correctly. Example:
4089 # struct Foo { x: u32 }
4090 # impl Foo { fn method(&self) {} }
4091 # let f = Foo { x: 0 };
4092 println!("{}", f.x);
4097 Attempted to access a private field on a struct.
4099 Erroneous code example:
4101 ```compile_fail,E0616
4104 x: u32, // So `x` is private in here.
4108 pub fn new() -> Foo { Foo { x: 0 } }
4112 let f = some_module::Foo::new();
4113 println!("{}", f.x); // error: field `x` of struct `some_module::Foo` is private
4116 If you want to access this field, you have two options:
4118 1) Set the field public:
4123 pub x: u32, // `x` is now public.
4127 pub fn new() -> Foo { Foo { x: 0 } }
4131 let f = some_module::Foo::new();
4132 println!("{}", f.x); // ok!
4135 2) Add a getter function:
4140 x: u32, // So `x` is still private in here.
4144 pub fn new() -> Foo { Foo { x: 0 } }
4146 // We create the getter function here:
4147 pub fn get_x(&self) -> &u32 { &self.x }
4151 let f = some_module::Foo::new();
4152 println!("{}", f.get_x()); // ok!
4157 Attempted to pass an invalid type of variable into a variadic function.
4159 Erroneous code example:
4161 ```compile_fail,E0617
4163 fn printf(c: *const i8, ...);
4167 printf(::std::ptr::null(), 0f32);
4168 // error: can't pass an `f32` to variadic function, cast to `c_double`
4172 Certain Rust types must be cast before passing them to a variadic function,
4173 because of arcane ABI rules dictated by the C standard. To fix the error,
4174 cast the value to the type specified by the error message (which you may need
4175 to import from `std::os::raw`).
4179 Attempted to call something which isn't a function nor a method.
4181 Erroneous code examples:
4183 ```compile_fail,E0618
4188 X::Entry(); // error: expected function, found `X::Entry`
4192 x(); // error: expected function, found `i32`
4195 Only functions and methods can be called using `()`. Example:
4198 // We declare a function:
4199 fn i_am_a_function() {}
4207 #### Note: this error code is no longer emitted by the compiler.
4208 The type-checker needed to know the type of an expression, but that type had not
4211 Erroneous code example:
4217 // Here, the type of `v` is not (yet) known, so we
4218 // cannot resolve this method call:
4219 v.to_uppercase(); // error: the type of this value must be known in
4226 Type inference typically proceeds from the top of the function to the bottom,
4227 figuring out types as it goes. In some cases -- notably method calls and
4228 overloadable operators like `*` -- the type checker may not have enough
4229 information *yet* to make progress. This can be true even if the rest of the
4230 function provides enough context (because the type-checker hasn't looked that
4231 far ahead yet). In this case, type annotations can be used to help it along.
4233 To fix this error, just specify the type of the variable. Example:
4236 let mut x: Vec<String> = vec![]; // We precise the type of the vec elements.
4239 v.to_uppercase(); // Since rustc now knows the type of the vec elements,
4240 // we can use `v`'s methods.
4248 A cast to an unsized type was attempted.
4250 Erroneous code example:
4252 ```compile_fail,E0620
4253 let x = &[1_usize, 2] as [usize]; // error: cast to unsized type: `&[usize; 2]`
4257 In Rust, some types don't have a known size at compile-time. For example, in a
4258 slice type like `[u32]`, the number of elements is not known at compile-time and
4259 hence the overall size cannot be computed. As a result, such types can only be
4260 manipulated through a reference (e.g., `&T` or `&mut T`) or other pointer-type
4261 (e.g., `Box` or `Rc`). Try casting to a reference instead:
4264 let x = &[1_usize, 2] as &[usize]; // ok!
4269 An intrinsic was declared without being a function.
4271 Erroneous code example:
4273 ```compile_fail,E0622
4274 #![feature(intrinsics)]
4275 extern "rust-intrinsic" {
4276 pub static breakpoint : unsafe extern "rust-intrinsic" fn();
4277 // error: intrinsic must be a function
4280 fn main() { unsafe { breakpoint(); } }
4283 An intrinsic is a function available for use in a given programming language
4284 whose implementation is handled specially by the compiler. In order to fix this
4285 error, just declare a function.
4289 A private item was used outside of its scope.
4291 Erroneous code example:
4293 ```compile_fail,E0624
4302 let foo = inner::Foo;
4303 foo.method(); // error: method `method` is private
4306 Two possibilities are available to solve this issue:
4308 1. Only use the item in the scope it has been defined:
4318 pub fn call_method(foo: &Foo) { // We create a public function.
4319 foo.method(); // Which calls the item.
4323 let foo = inner::Foo;
4324 inner::call_method(&foo); // And since the function is public, we can call the
4325 // method through it.
4328 2. Make the item public:
4335 pub fn method(&self) {} // It's now public.
4339 let foo = inner::Foo;
4340 foo.method(); // Ok!
4345 This error indicates that the struct, enum or enum variant must be matched
4346 non-exhaustively as it has been marked as `non_exhaustive`.
4348 When applied within a crate, downstream users of the crate will need to use the
4349 `_` pattern when matching enums and use the `..` pattern when matching structs.
4350 Downstream crates cannot match against non-exhaustive enum variants.
4352 For example, in the below example, since the enum is marked as
4353 `non_exhaustive`, it is required that downstream crates match non-exhaustively
4356 ```rust,ignore (pseudo-Rust)
4357 use std::error::Error as StdError;
4359 #[non_exhaustive] pub enum Error {
4364 impl StdError for Error {
4365 fn description(&self) -> &str {
4366 // This will not error, despite being marked as non_exhaustive, as this
4367 // enum is defined within the current crate, it can be matched
4370 Message(ref s) => s,
4371 Other => "other or unknown error",
4377 An example of matching non-exhaustively on the above enum is provided below:
4379 ```rust,ignore (pseudo-Rust)
4382 // This will not error as the non_exhaustive Error enum has been matched with a
4385 Message(ref s) => ...,
4391 Similarly, for structs, match with `..` to avoid this error.
4395 This error indicates that the struct, enum or enum variant cannot be
4396 instantiated from outside of the defining crate as it has been marked
4397 as `non_exhaustive` and as such more fields/variants may be added in
4398 future that could cause adverse side effects for this code.
4400 It is recommended that you look for a `new` function or equivalent in the
4401 crate's documentation.
4405 This error indicates that there is a mismatch between generic parameters and
4406 impl Trait parameters in a trait declaration versus its impl.
4408 ```compile_fail,E0643
4410 fn foo(&self, _: &impl Iterator);
4413 fn foo<U: Iterator>(&self, _: &U) { } // error method `foo` has incompatible
4414 // signature for trait
4420 It is not possible to define `main` with a where clause.
4421 Erroneous code example:
4423 ```compile_fail,E0646
4424 fn main() where i32: Copy { // error: main function is not allowed to have
4431 It is not possible to define `start` with a where clause.
4432 Erroneous code example:
4434 ```compile_fail,E0647
4438 fn start(_: isize, _: *const *const u8) -> isize where (): Copy {
4439 //^ error: start function is not allowed to have a where clause
4446 `export_name` attributes may not contain null characters (`\0`).
4448 ```compile_fail,E0648
4449 #[export_name="\0foo"] // error: `export_name` may not contain null characters
4455 This error indicates that the numeric value for the method being passed exists
4456 but the type of the numeric value or binding could not be identified.
4458 The error happens on numeric literals:
4460 ```compile_fail,E0689
4464 and on numeric bindings without an identified concrete type:
4466 ```compile_fail,E0689
4468 x.neg(); // same error as above
4471 Because of this, you must give the numeric literal or binding a type:
4476 let _ = 2.0_f32.neg();
4479 let _ = (2.0 as f32).neg();
4484 A struct with the representation hint `repr(transparent)` had zero or more than
4485 on fields that were not guaranteed to be zero-sized.
4487 Erroneous code example:
4489 ```compile_fail,E0690
4490 #[repr(transparent)]
4491 struct LengthWithUnit<U> { // error: transparent struct needs exactly one
4492 value: f32, // non-zero-sized field, but has 2
4497 Because transparent structs are represented exactly like one of their fields at
4498 run time, said field must be uniquely determined. If there is no field, or if
4499 there are multiple fields, it is not clear how the struct should be represented.
4500 Note that fields of zero-typed types (e.g., `PhantomData`) can also exist
4501 alongside the field that contains the actual data, they do not count for this
4502 error. When generic types are involved (as in the above example), an error is
4503 reported because the type parameter could be non-zero-sized.
4505 To combine `repr(transparent)` with type parameters, `PhantomData` may be
4509 use std::marker::PhantomData;
4511 #[repr(transparent)]
4512 struct LengthWithUnit<U> {
4514 unit: PhantomData<U>,
4520 A struct with the `repr(transparent)` representation hint contains a zero-sized
4521 field that requires non-trivial alignment.
4523 Erroneous code example:
4525 ```compile_fail,E0691
4526 #![feature(repr_align)]
4529 struct ForceAlign32;
4531 #[repr(transparent)]
4532 struct Wrapper(f32, ForceAlign32); // error: zero-sized field in transparent
4533 // struct has alignment larger than 1
4536 A transparent struct is supposed to be represented exactly like the piece of
4537 data it contains. Zero-sized fields with different alignment requirements
4538 potentially conflict with this property. In the example above, `Wrapper` would
4539 have to be aligned to 32 bytes even though `f32` has a smaller alignment
4542 Consider removing the over-aligned zero-sized field:
4545 #[repr(transparent)]
4546 struct Wrapper(f32);
4549 Alternatively, `PhantomData<T>` has alignment 1 for all `T`, so you can use it
4550 if you need to keep the field for some reason:
4553 #![feature(repr_align)]
4555 use std::marker::PhantomData;
4558 struct ForceAlign32;
4560 #[repr(transparent)]
4561 struct Wrapper(f32, PhantomData<ForceAlign32>);
4564 Note that empty arrays `[T; 0]` have the same alignment requirement as the
4565 element type `T`. Also note that the error is conservatively reported even when
4566 the alignment of the zero-sized type is less than or equal to the data field's
4572 A method was called on a raw pointer whose inner type wasn't completely known.
4574 For example, you may have done something like:
4577 # #![deny(warnings)]
4579 let bar = foo as *const _;
4585 Here, the type of `bar` isn't known; it could be a pointer to anything. Instead,
4586 specify a type for the pointer (preferably something that makes sense for the
4587 thing you're pointing to):
4591 let bar = foo as *const i32;
4597 Even though `is_null()` exists as a method on any raw pointer, Rust shows this
4598 error because Rust allows for `self` to have arbitrary types (behind the
4599 arbitrary_self_types feature flag).
4601 This means that someone can specify such a function:
4603 ```ignore (cannot-doctest-feature-doesnt-exist-yet)
4605 fn is_null(self: *const Self) -> bool {
4606 // do something else
4611 and now when you call `.is_null()` on a raw pointer to `Foo`, there's ambiguity.
4613 Given that we don't know what type the pointer is, and there's potential
4614 ambiguity for some types, we disallow calling methods on raw pointers when
4615 the type is unknown.
4619 A `#[marker]` trait contained an associated item.
4621 The items of marker traits cannot be overridden, so there's no need to have them
4622 when they cannot be changed per-type anyway. If you wanted them for ergonomic
4623 reasons, consider making an extension trait instead.
4627 An `impl` for a `#[marker]` trait tried to override an associated item.
4629 Because marker traits are allowed to have multiple implementations for the same
4630 type, it's not allowed to override anything in those implementations, as it
4631 would be ambiguous which override should actually be used.
4636 An `impl Trait` type expands to a recursive type.
4638 An `impl Trait` type must be expandable to a concrete type that contains no
4639 `impl Trait` types. For example the following example tries to create an
4640 `impl Trait` type `T` that is equal to `[T, T]`:
4642 ```compile_fail,E0720
4643 fn make_recursive_type() -> impl Sized {
4644 [make_recursive_type(), make_recursive_type()]
4651 register_diagnostics! {
4652 // E0035, merged into E0087/E0089
4653 // E0036, merged into E0087/E0089
4659 // E0122, // bounds in type aliases are ignored, turned into proper lint
4664 // E0159, // use of trait `{}` as struct constructor
4665 // E0163, // merged into E0071
4668 // E0172, // non-trait found in a type sum, moved to resolve
4669 // E0173, // manual implementations of unboxed closure traits are experimental
4671 // E0182, // merged into E0229
4673 // E0187, // can't infer the kind of the closure
4674 // E0188, // can not cast an immutable reference to a mutable pointer
4675 // E0189, // deprecated: can only cast a boxed pointer to a boxed object
4676 // E0190, // deprecated: can only cast a &-pointer to an &-object
4677 // E0196, // cannot determine a type for this closure
4678 E0203, // type parameter has more than one relaxed default bound,
4679 // and only one is supported
4681 // E0209, // builtin traits can only be implemented on structs or enums
4682 E0212, // cannot extract an associated type from a higher-ranked trait bound
4683 // E0213, // associated types are not accepted in this context
4684 // E0215, // angle-bracket notation is not stable with `Fn`
4685 // E0216, // parenthetical notation is only stable with `Fn`
4686 // E0217, // ambiguous associated type, defined in multiple supertraits
4687 // E0218, // no associated type defined
4688 // E0219, // associated type defined in higher-ranked supertrait
4689 // E0222, // Error code E0045 (variadic function must have C or cdecl calling
4690 // convention) duplicate
4691 E0224, // at least one non-builtin train is required for an object type
4692 E0227, // ambiguous lifetime bound, explicit lifetime bound required
4693 E0228, // explicit lifetime bound required
4696 // E0235, // structure constructor specifies a structure of type but
4697 // E0236, // no lang item for range syntax
4698 // E0237, // no lang item for range syntax
4699 // E0238, // parenthesized parameters may only be used with a trait
4700 // E0239, // `next` method of `Iterator` trait has unexpected type
4704 // E0245, // not a trait
4705 // E0246, // invalid recursive type
4707 // E0248, // value used as a type, now reported earlier during resolution as E0412
4709 E0307, // invalid method `self` type
4710 // E0319, // trait impls for defaulted traits allowed just for structs/enums
4711 // E0372, // coherence not object safe
4712 E0377, // the trait `CoerceUnsized` may only be implemented for a coercion
4713 // between structures with the same definition
4714 // E0558, // replaced with a generic attribute input check
4715 E0533, // `{}` does not name a unit variant, unit struct or a constant
4716 // E0563, // cannot determine a type for this `impl Trait`: {} // removed in 6383de15
4717 E0564, // only named lifetimes are allowed in `impl Trait`,
4718 // but `{}` was found in the type `{}`
4719 E0587, // type has conflicting packed and align representation hints
4720 E0588, // packed type cannot transitively contain a `[repr(align)]` type
4721 E0592, // duplicate definitions with name `{}`
4722 // E0611, // merged into E0616
4723 // E0612, // merged into E0609
4724 // E0613, // Removed (merged with E0609)
4725 E0627, // yield statement outside of generator literal
4726 E0632, // cannot provide explicit type parameters when `impl Trait` is used in
4727 // argument position.
4728 E0634, // type has conflicting packed representaton hints
4729 E0640, // infer outlives requirements
4730 E0641, // cannot cast to/from a pointer with an unknown kind
4731 E0645, // trait aliases not finished
4732 E0719, // duplicate values for associated type binding
4733 E0722, // Malformed #[optimize] attribute
4734 E0724, // `#[ffi_returns_twice]` is only allowed in foreign functions