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 _implementing type_ of the impl, e.g. `impl<T> Foo<T>`
1946 - for a trait impl, it appears in the _implemented trait_, e.g.
1947 `impl<T> SomeTrait<T> for Foo`
1948 - it is bound as an associated type, e.g. `impl<T, U> SomeTrait for T
1949 where T: AnotherTrait<AssocType=U>`
1953 Suppose we have a struct `Foo` and we would like to define some methods for it.
1954 The following definition leads to a compiler error:
1956 ```compile_fail,E0207
1959 impl<T: Default> Foo {
1960 // error: the type parameter `T` is not constrained by the impl trait, self
1961 // type, or predicates [E0207]
1962 fn get(&self) -> T {
1963 <T as Default>::default()
1968 The problem is that the parameter `T` does not appear in the implementing type
1969 (`Foo`) of the impl. In this case, we can fix the error by moving the type
1970 parameter from the `impl` to the method `get`:
1976 // Move the type parameter from the impl to the method
1978 fn get<T: Default>(&self) -> T {
1979 <T as Default>::default()
1986 As another example, suppose we have a `Maker` trait and want to establish a
1987 type `FooMaker` that makes `Foo`s:
1989 ```compile_fail,E0207
1992 fn make(&mut self) -> Self::Item;
2001 impl<T: Default> Maker for FooMaker {
2002 // error: the type parameter `T` is not constrained by the impl trait, self
2003 // type, or predicates [E0207]
2006 fn make(&mut self) -> Foo<T> {
2007 Foo { foo: <T as Default>::default() }
2012 This fails to compile because `T` does not appear in the trait or in the
2015 One way to work around this is to introduce a phantom type parameter into
2016 `FooMaker`, like so:
2019 use std::marker::PhantomData;
2023 fn make(&mut self) -> Self::Item;
2030 // Add a type parameter to `FooMaker`
2031 struct FooMaker<T> {
2032 phantom: PhantomData<T>,
2035 impl<T: Default> Maker for FooMaker<T> {
2038 fn make(&mut self) -> Foo<T> {
2040 foo: <T as Default>::default(),
2046 Another way is to do away with the associated type in `Maker` and use an input
2047 type parameter instead:
2050 // Use a type parameter instead of an associated type here
2052 fn make(&mut self) -> Item;
2061 impl<T: Default> Maker<Foo<T>> for FooMaker {
2062 fn make(&mut self) -> Foo<T> {
2063 Foo { foo: <T as Default>::default() }
2068 ### Additional information
2070 For more information, please see [RFC 447].
2072 [RFC 447]: https://github.com/rust-lang/rfcs/blob/master/text/0447-no-unused-impl-parameters.md
2076 This error indicates a violation of one of Rust's orphan rules for trait
2077 implementations. The rule concerns the use of type parameters in an
2078 implementation of a foreign trait (a trait defined in another crate), and
2079 states that type parameters must be "covered" by a local type. To understand
2080 what this means, it is perhaps easiest to consider a few examples.
2082 If `ForeignTrait` is a trait defined in some external crate `foo`, then the
2083 following trait `impl` is an error:
2085 ```compile_fail,E0210
2086 # #[cfg(for_demonstration_only)]
2088 # #[cfg(for_demonstration_only)]
2089 use foo::ForeignTrait;
2090 # use std::panic::UnwindSafe as ForeignTrait;
2092 impl<T> ForeignTrait for T { } // error
2096 To work around this, it can be covered with a local type, `MyType`:
2099 # use std::panic::UnwindSafe as ForeignTrait;
2100 struct MyType<T>(T);
2101 impl<T> ForeignTrait for MyType<T> { } // Ok
2104 Please note that a type alias is not sufficient.
2106 For another example of an error, suppose there's another trait defined in `foo`
2107 named `ForeignTrait2` that takes two type parameters. Then this `impl` results
2108 in the same rule violation:
2110 ```ignore (cannot-doctest-multicrate-project)
2112 impl<T> ForeignTrait2<T, MyType<T>> for MyType2 { } // error
2115 The reason for this is that there are two appearances of type parameter `T` in
2116 the `impl` header, both as parameters for `ForeignTrait2`. The first appearance
2117 is uncovered, and so runs afoul of the orphan rule.
2119 Consider one more example:
2121 ```ignore (cannot-doctest-multicrate-project)
2122 impl<T> ForeignTrait2<MyType<T>, T> for MyType2 { } // Ok
2125 This only differs from the previous `impl` in that the parameters `T` and
2126 `MyType<T>` for `ForeignTrait2` have been swapped. This example does *not*
2127 violate the orphan rule; it is permitted.
2129 To see why that last example was allowed, you need to understand the general
2130 rule. Unfortunately this rule is a bit tricky to state. Consider an `impl`:
2132 ```ignore (only-for-syntax-highlight)
2133 impl<P1, ..., Pm> ForeignTrait<T1, ..., Tn> for T0 { ... }
2136 where `P1, ..., Pm` are the type parameters of the `impl` and `T0, ..., Tn`
2137 are types. One of the types `T0, ..., Tn` must be a local type (this is another
2138 orphan rule, see the explanation for E0117). Let `i` be the smallest integer
2139 such that `Ti` is a local type. Then no type parameter can appear in any of the
2142 For information on the design of the orphan rules, see [RFC 1023].
2144 [RFC 1023]: https://github.com/rust-lang/rfcs/blob/master/text/1023-rebalancing-coherence.md
2149 You used a function or type which doesn't fit the requirements for where it was
2150 used. Erroneous code examples:
2153 #![feature(intrinsics)]
2155 extern "rust-intrinsic" {
2156 fn size_of<T>(); // error: intrinsic has wrong type
2161 fn main() -> i32 { 0 }
2162 // error: main function expects type: `fn() {main}`: expected (), found i32
2169 // error: mismatched types in range: expected u8, found i8
2179 fn x(self: Rc<Foo>) {}
2180 // error: mismatched self type: expected `Foo`: expected struct
2181 // `Foo`, found struct `alloc::rc::Rc`
2185 For the first code example, please check the function definition. Example:
2188 #![feature(intrinsics)]
2190 extern "rust-intrinsic" {
2191 fn size_of<T>() -> usize; // ok!
2195 The second case example is a bit particular : the main function must always
2196 have this definition:
2202 They never take parameters and never return types.
2204 For the third example, when you match, all patterns must have the same type
2205 as the type you're matching on. Example:
2211 0u8..=3u8 => (), // ok!
2216 And finally, for the last example, only `Box<Self>`, `&Self`, `Self`,
2217 or `&mut Self` work as explicit self parameters. Example:
2223 fn x(self: Box<Foo>) {} // ok!
2230 You used an associated type which isn't defined in the trait.
2231 Erroneous code example:
2233 ```compile_fail,E0220
2238 type Foo = T1<F=i32>; // error: associated type `F` not found for `T1`
2245 // error: Baz is used but not declared
2246 fn return_bool(&self, _: &Self::Bar, _: &Self::Baz) -> bool;
2250 Make sure that you have defined the associated type in the trait body.
2251 Also, verify that you used the right trait or you didn't misspell the
2252 associated type name. Example:
2259 type Foo = T1<Bar=i32>; // ok!
2265 type Baz; // we declare `Baz` in our trait.
2267 // and now we can use it here:
2268 fn return_bool(&self, _: &Self::Bar, _: &Self::Baz) -> bool;
2274 An attempt was made to retrieve an associated type, but the type was ambiguous.
2277 ```compile_fail,E0221
2293 In this example, `Foo` defines an associated type `A`. `Bar` inherits that type
2294 from `Foo`, and defines another associated type of the same name. As a result,
2295 when we attempt to use `Self::A`, it's ambiguous whether we mean the `A` defined
2296 by `Foo` or the one defined by `Bar`.
2298 There are two options to work around this issue. The first is simply to rename
2299 one of the types. Alternatively, one can specify the intended type using the
2313 let _: <Self as Bar>::A;
2320 An attempt was made to retrieve an associated type, but the type was ambiguous.
2323 ```compile_fail,E0223
2324 trait MyTrait {type X; }
2327 let foo: MyTrait::X;
2331 The problem here is that we're attempting to take the type of X from MyTrait.
2332 Unfortunately, the type of X is not defined, because it's only made concrete in
2333 implementations of the trait. A working version of this code might look like:
2336 trait MyTrait {type X; }
2339 impl MyTrait for MyStruct {
2344 let foo: <MyStruct as MyTrait>::X;
2348 This syntax specifies that we want the X type from MyTrait, as made concrete in
2349 MyStruct. The reason that we cannot simply use `MyStruct::X` is that MyStruct
2350 might implement two different traits with identically-named associated types.
2351 This syntax allows disambiguation between the two.
2355 You attempted to use multiple types as bounds for a closure or trait object.
2356 Rust does not currently support this. A simple example that causes this error:
2358 ```compile_fail,E0225
2360 let _: Box<dyn std::io::Read + std::io::Write>;
2364 Auto traits such as Send and Sync are an exception to this rule:
2365 It's possible to have bounds of one non-builtin trait, plus any number of
2366 auto traits. For example, the following compiles correctly:
2370 let _: Box<dyn std::io::Read + Send + Sync>;
2376 An associated type binding was done outside of the type parameter declaration
2377 and `where` clause. Erroneous code example:
2379 ```compile_fail,E0229
2382 fn boo(&self) -> <Self as Foo>::A;
2387 impl Foo for isize {
2389 fn boo(&self) -> usize { 42 }
2392 fn baz<I>(x: &<I as Foo<A=Bar>>::A) {}
2393 // error: associated type bindings are not allowed here
2396 To solve this error, please move the type bindings in the type parameter
2401 # trait Foo { type A; }
2402 fn baz<I: Foo<A=Bar>>(x: &<I as Foo>::A) {} // ok!
2405 Or in the `where` clause:
2409 # trait Foo { type A; }
2410 fn baz<I>(x: &<I as Foo>::A) where I: Foo<A=Bar> {}
2415 #### Note: this error code is no longer emitted by the compiler.
2417 This error indicates that not enough type parameters were found in a type or
2420 For example, the `Foo` struct below is defined to be generic in `T`, but the
2421 type parameter is missing in the definition of `Bar`:
2423 ```compile_fail,E0107
2424 struct Foo<T> { x: T }
2426 struct Bar { x: Foo }
2431 #### Note: this error code is no longer emitted by the compiler.
2433 This error indicates that too many type parameters were found in a type or
2436 For example, the `Foo` struct below has no type parameters, but is supplied
2437 with two in the definition of `Bar`:
2439 ```compile_fail,E0107
2440 struct Foo { x: bool }
2442 struct Bar<S, T> { x: Foo<S, T> }
2447 A cross-crate opt-out trait was implemented on something which wasn't a struct
2448 or enum type. Erroneous code example:
2450 ```compile_fail,E0321
2451 #![feature(optin_builtin_traits)]
2455 impl !Sync for Foo {}
2457 unsafe impl Send for &'static Foo {}
2458 // error: cross-crate traits with a default impl, like `core::marker::Send`,
2459 // can only be implemented for a struct/enum type, not
2463 Only structs and enums are permitted to impl Send, Sync, and other opt-out
2464 trait, and the struct or enum must be local to the current crate. So, for
2465 example, `unsafe impl Send for Rc<Foo>` is not allowed.
2469 The `Sized` trait is a special trait built-in to the compiler for types with a
2470 constant size known at compile-time. This trait is automatically implemented
2471 for types as needed by the compiler, and it is currently disallowed to
2472 explicitly implement it for a type.
2476 An associated const was implemented when another trait item was expected.
2477 Erroneous code example:
2479 ```compile_fail,E0323
2488 // error: item `N` is an associated const, which doesn't match its
2489 // trait `<Bar as Foo>`
2493 Please verify that the associated const wasn't misspelled and the correct trait
2494 was implemented. Example:
2504 type N = u32; // ok!
2518 const N : u32 = 0; // ok!
2524 A method was implemented when another trait item was expected. Erroneous
2527 ```compile_fail,E0324
2538 // error: item `N` is an associated method, which doesn't match its
2539 // trait `<Bar as Foo>`
2543 To fix this error, please verify that the method name wasn't misspelled and
2544 verify that you are indeed implementing the correct trait items. Example:
2564 An associated type was implemented when another trait item was expected.
2565 Erroneous code example:
2567 ```compile_fail,E0325
2576 // error: item `N` is an associated type, which doesn't match its
2577 // trait `<Bar as Foo>`
2581 Please verify that the associated type name wasn't misspelled and your
2582 implementation corresponds to the trait definition. Example:
2592 type N = u32; // ok!
2606 const N : u32 = 0; // ok!
2612 The types of any associated constants in a trait implementation must match the
2613 types in the trait definition. This error indicates that there was a mismatch.
2615 Here's an example of this error:
2617 ```compile_fail,E0326
2625 const BAR: u32 = 5; // error, expected bool, found u32
2631 The Unsize trait should not be implemented directly. All implementations of
2632 Unsize are provided automatically by the compiler.
2634 Erroneous code example:
2636 ```compile_fail,E0328
2639 use std::marker::Unsize;
2643 impl<T> Unsize<T> for MyType {}
2646 If you are defining your own smart pointer type and would like to enable
2647 conversion from a sized to an unsized type with the
2648 [DST coercion system][RFC 982], use [`CoerceUnsized`] instead.
2651 #![feature(coerce_unsized)]
2653 use std::ops::CoerceUnsized;
2655 pub struct MyType<T: ?Sized> {
2656 field_with_unsized_type: T,
2659 impl<T, U> CoerceUnsized<MyType<U>> for MyType<T>
2660 where T: CoerceUnsized<U> {}
2663 [RFC 982]: https://github.com/rust-lang/rfcs/blob/master/text/0982-dst-coercion.md
2664 [`CoerceUnsized`]: https://doc.rust-lang.org/std/ops/trait.CoerceUnsized.html
2668 // Associated consts can now be accessed through generic type parameters, and
2669 // this error is no longer emitted.
2671 // FIXME: consider whether to leave it in the error index, or remove it entirely
2672 // as associated consts is not stabilized yet.
2675 An attempt was made to access an associated constant through either a generic
2676 type parameter or `Self`. This is not supported yet. An example causing this
2677 error is shown below:
2686 impl Foo for MyStruct {
2687 const BAR: f64 = 0f64;
2690 fn get_bar_bad<F: Foo>(t: F) -> f64 {
2695 Currently, the value of `BAR` for a particular type can only be accessed
2696 through a concrete type, as shown below:
2705 fn get_bar_good() -> f64 {
2706 <MyStruct as Foo>::BAR
2713 An attempt was made to implement `Drop` on a concrete specialization of a
2714 generic type. An example is shown below:
2716 ```compile_fail,E0366
2721 impl Drop for Foo<u32> {
2722 fn drop(&mut self) {}
2726 This code is not legal: it is not possible to specialize `Drop` to a subset of
2727 implementations of a generic type. One workaround for this is to wrap the
2728 generic type, as shown below:
2740 fn drop(&mut self) {}
2746 An attempt was made to implement `Drop` on a specialization of a generic type.
2747 An example is shown below:
2749 ```compile_fail,E0367
2752 struct MyStruct<T> {
2756 impl<T: Foo> Drop for MyStruct<T> {
2757 fn drop(&mut self) {}
2761 This code is not legal: it is not possible to specialize `Drop` to a subset of
2762 implementations of a generic type. In order for this code to work, `MyStruct`
2763 must also require that `T` implements `Foo`. Alternatively, another option is
2764 to wrap the generic type in another that specializes appropriately:
2769 struct MyStruct<T> {
2773 struct MyStructWrapper<T: Foo> {
2777 impl <T: Foo> Drop for MyStructWrapper<T> {
2778 fn drop(&mut self) {}
2784 This error indicates that a binary assignment operator like `+=` or `^=` was
2785 applied to a type that doesn't support it. For example:
2787 ```compile_fail,E0368
2788 let mut x = 12f32; // error: binary operation `<<` cannot be applied to
2794 To fix this error, please check that this type implements this binary
2798 let mut x = 12u32; // the `u32` type does implement the `ShlAssign` trait
2803 It is also possible to overload most operators for your own type by
2804 implementing the `[OP]Assign` traits from `std::ops`.
2806 Another problem you might be facing is this: suppose you've overloaded the `+`
2807 operator for some type `Foo` by implementing the `std::ops::Add` trait for
2808 `Foo`, but you find that using `+=` does not work, as in this example:
2810 ```compile_fail,E0368
2818 fn add(self, rhs: Foo) -> Foo {
2824 let mut x: Foo = Foo(5);
2825 x += Foo(7); // error, `+= cannot be applied to the type `Foo`
2829 This is because `AddAssign` is not automatically implemented, so you need to
2830 manually implement it for your type.
2834 A binary operation was attempted on a type which doesn't support it.
2835 Erroneous code example:
2837 ```compile_fail,E0369
2838 let x = 12f32; // error: binary operation `<<` cannot be applied to
2844 To fix this error, please check that this type implements this binary
2848 let x = 12u32; // the `u32` type does implement it:
2849 // https://doc.rust-lang.org/stable/std/ops/trait.Shl.html
2854 It is also possible to overload most operators for your own type by
2855 implementing traits from `std::ops`.
2857 String concatenation appends the string on the right to the string on the
2858 left and may require reallocation. This requires ownership of the string
2859 on the left. If something should be added to a string literal, move the
2860 literal to the heap by allocating it with `to_owned()` like in
2861 `"Your text".to_owned()`.
2866 The maximum value of an enum was reached, so it cannot be automatically
2867 set in the next enum value. Erroneous code example:
2869 ```compile_fail,E0370
2872 X = 0x7fffffffffffffff,
2873 Y, // error: enum discriminant overflowed on value after
2874 // 9223372036854775807: i64; set explicitly via
2875 // Y = -9223372036854775808 if that is desired outcome
2879 To fix this, please set manually the next enum value or put the enum variant
2880 with the maximum value at the end of the enum. Examples:
2885 X = 0x7fffffffffffffff,
2896 X = 0x7fffffffffffffff,
2902 When `Trait2` is a subtrait of `Trait1` (for example, when `Trait2` has a
2903 definition like `trait Trait2: Trait1 { ... }`), it is not allowed to implement
2904 `Trait1` for `Trait2`. This is because `Trait2` already implements `Trait1` by
2905 definition, so it is not useful to do this.
2909 ```compile_fail,E0371
2910 trait Foo { fn foo(&self) { } }
2914 impl Bar for Baz { } // error, `Baz` implements `Bar` by definition
2915 impl Foo for Baz { } // error, `Baz` implements `Bar` which implements `Foo`
2916 impl Baz for Baz { } // error, `Baz` (trivially) implements `Baz`
2917 impl Baz for Bar { } // Note: This is OK
2922 A struct without a field containing an unsized type cannot implement
2923 `CoerceUnsized`. An [unsized type][1] is any type that the compiler
2924 doesn't know the length or alignment of at compile time. Any struct
2925 containing an unsized type is also unsized.
2927 [1]: https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait
2929 Example of erroneous code:
2931 ```compile_fail,E0374
2932 #![feature(coerce_unsized)]
2933 use std::ops::CoerceUnsized;
2935 struct Foo<T: ?Sized> {
2939 // error: Struct `Foo` has no unsized fields that need `CoerceUnsized`.
2940 impl<T, U> CoerceUnsized<Foo<U>> for Foo<T>
2941 where T: CoerceUnsized<U> {}
2944 `CoerceUnsized` is used to coerce one struct containing an unsized type
2945 into another struct containing a different unsized type. If the struct
2946 doesn't have any fields of unsized types then you don't need explicit
2947 coercion to get the types you want. To fix this you can either
2948 not try to implement `CoerceUnsized` or you can add a field that is
2949 unsized to the struct.
2954 #![feature(coerce_unsized)]
2955 use std::ops::CoerceUnsized;
2957 // We don't need to impl `CoerceUnsized` here.
2962 // We add the unsized type field to the struct.
2963 struct Bar<T: ?Sized> {
2968 // The struct has an unsized field so we can implement
2969 // `CoerceUnsized` for it.
2970 impl<T, U> CoerceUnsized<Bar<U>> for Bar<T>
2971 where T: CoerceUnsized<U> {}
2974 Note that `CoerceUnsized` is mainly used by smart pointers like `Box`, `Rc`
2975 and `Arc` to be able to mark that they can coerce unsized types that they
2980 A struct with more than one field containing an unsized type cannot implement
2981 `CoerceUnsized`. This only occurs when you are trying to coerce one of the
2982 types in your struct to another type in the struct. In this case we try to
2983 impl `CoerceUnsized` from `T` to `U` which are both types that the struct
2984 takes. An [unsized type][1] is any type that the compiler doesn't know the
2985 length or alignment of at compile time. Any struct containing an unsized type
2988 Example of erroneous code:
2990 ```compile_fail,E0375
2991 #![feature(coerce_unsized)]
2992 use std::ops::CoerceUnsized;
2994 struct Foo<T: ?Sized, U: ?Sized> {
3000 // error: Struct `Foo` has more than one unsized field.
3001 impl<T, U> CoerceUnsized<Foo<U, T>> for Foo<T, U> {}
3004 `CoerceUnsized` only allows for coercion from a structure with a single
3005 unsized type field to another struct with a single unsized type field.
3006 In fact Rust only allows for a struct to have one unsized type in a struct
3007 and that unsized type must be the last field in the struct. So having two
3008 unsized types in a single struct is not allowed by the compiler. To fix this
3009 use only one field containing an unsized type in the struct and then use
3010 multiple structs to manage each unsized type field you need.
3015 #![feature(coerce_unsized)]
3016 use std::ops::CoerceUnsized;
3018 struct Foo<T: ?Sized> {
3023 impl <T, U> CoerceUnsized<Foo<U>> for Foo<T>
3024 where T: CoerceUnsized<U> {}
3026 fn coerce_foo<T: CoerceUnsized<U>, U>(t: T) -> Foo<U> {
3027 Foo { a: 12i32, b: t } // we use coercion to get the `Foo<U>` type we need
3031 [1]: https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait
3035 The type you are trying to impl `CoerceUnsized` for is not a struct.
3036 `CoerceUnsized` can only be implemented for a struct. Unsized types are
3037 already able to be coerced without an implementation of `CoerceUnsized`
3038 whereas a struct containing an unsized type needs to know the unsized type
3039 field it's containing is able to be coerced. An [unsized type][1]
3040 is any type that the compiler doesn't know the length or alignment of at
3041 compile time. Any struct containing an unsized type is also unsized.
3043 [1]: https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait
3045 Example of erroneous code:
3047 ```compile_fail,E0376
3048 #![feature(coerce_unsized)]
3049 use std::ops::CoerceUnsized;
3051 struct Foo<T: ?Sized> {
3055 // error: The type `U` is not a struct
3056 impl<T, U> CoerceUnsized<U> for Foo<T> {}
3059 The `CoerceUnsized` trait takes a struct type. Make sure the type you are
3060 providing to `CoerceUnsized` is a struct with only the last field containing an
3066 #![feature(coerce_unsized)]
3067 use std::ops::CoerceUnsized;
3073 // The `Foo<U>` is a struct so `CoerceUnsized` can be implemented
3074 impl<T, U> CoerceUnsized<Foo<U>> for Foo<T> where T: CoerceUnsized<U> {}
3077 Note that in Rust, structs can only contain an unsized type if the field
3078 containing the unsized type is the last and only unsized type field in the
3083 The `DispatchFromDyn` trait currently can only be implemented for
3084 builtin pointer types and structs that are newtype wrappers around them
3085 — that is, the struct must have only one field (except for`PhantomData`),
3086 and that field must itself implement `DispatchFromDyn`.
3091 #![feature(dispatch_from_dyn, unsize)]
3094 ops::DispatchFromDyn,
3097 struct Ptr<T: ?Sized>(*const T);
3099 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Ptr<U>> for Ptr<T>
3106 #![feature(dispatch_from_dyn)]
3108 ops::DispatchFromDyn,
3109 marker::PhantomData,
3114 _phantom: PhantomData<()>,
3117 impl<T, U> DispatchFromDyn<Wrapper<U>> for Wrapper<T>
3119 T: DispatchFromDyn<U>,
3123 Example of illegal `DispatchFromDyn` implementation
3124 (illegal because of extra field)
3126 ```compile-fail,E0378
3127 #![feature(dispatch_from_dyn)]
3128 use std::ops::DispatchFromDyn;
3130 struct WrapperExtraField<T> {
3135 impl<T, U> DispatchFromDyn<WrapperExtraField<U>> for WrapperExtraField<T>
3137 T: DispatchFromDyn<U>,
3143 You tried to implement methods for a primitive type. Erroneous code example:
3145 ```compile_fail,E0390
3151 // error: only a single inherent implementation marked with
3152 // `#[lang = "mut_ptr"]` is allowed for the `*mut T` primitive
3155 This isn't allowed, but using a trait to implement a method is a good solution.
3167 impl Bar for *mut Foo {
3174 This error indicates that a type or lifetime parameter has been declared
3175 but not actually used. Here is an example that demonstrates the error:
3177 ```compile_fail,E0392
3183 If the type parameter was included by mistake, this error can be fixed
3184 by simply removing the type parameter, as shown below:
3192 Alternatively, if the type parameter was intentionally inserted, it must be
3193 used. A simple fix is shown below:
3201 This error may also commonly be found when working with unsafe code. For
3202 example, when using raw pointers one may wish to specify the lifetime for
3203 which the pointed-at data is valid. An initial attempt (below) causes this
3206 ```compile_fail,E0392
3212 We want to express the constraint that Foo should not outlive `'a`, because
3213 the data pointed to by `T` is only valid for that lifetime. The problem is
3214 that there are no actual uses of `'a`. It's possible to work around this
3215 by adding a PhantomData type to the struct, using it to tell the compiler
3216 to act as if the struct contained a borrowed reference `&'a T`:
3219 use std::marker::PhantomData;
3221 struct Foo<'a, T: 'a> {
3223 phantom: PhantomData<&'a T>
3227 [PhantomData] can also be used to express information about unused type
3230 [PhantomData]: https://doc.rust-lang.org/std/marker/struct.PhantomData.html
3234 A type parameter which references `Self` in its default value was not specified.
3235 Example of erroneous code:
3237 ```compile_fail,E0393
3240 fn together_we_will_rule_the_galaxy(son: &A) {}
3241 // error: the type parameter `T` must be explicitly specified in an
3242 // object type because its default value `Self` references the
3246 A trait object is defined over a single, fully-defined trait. With a regular
3247 default parameter, this parameter can just be substituted in. However, if the
3248 default parameter is `Self`, the trait changes for each concrete type; i.e.
3249 `i32` will be expected to implement `A<i32>`, `bool` will be expected to
3250 implement `A<bool>`, etc... These types will not share an implementation of a
3251 fully-defined trait; instead they share implementations of a trait with
3252 different parameters substituted in for each implementation. This is
3253 irreconcilable with what we need to make a trait object work, and is thus
3254 disallowed. Making the trait concrete by explicitly specifying the value of the
3255 defaulted parameter will fix this issue. Fixed example:
3260 fn together_we_will_rule_the_galaxy(son: &A<i32>) {} // Ok!
3265 You implemented a trait, overriding one or more of its associated types but did
3266 not reimplement its default methods.
3268 Example of erroneous code:
3270 ```compile_fail,E0399
3271 #![feature(associated_type_defaults)]
3279 // error - the following trait items need to be reimplemented as
3280 // `Assoc` was overridden: `bar`
3285 To fix this, add an implementation for each default method from the trait:
3288 #![feature(associated_type_defaults)]
3297 fn bar(&self) {} // ok!
3303 The functional record update syntax is only allowed for structs. (Struct-like
3304 enum variants don't qualify, for example.)
3306 Erroneous code example:
3308 ```compile_fail,E0436
3309 enum PublicationFrequency {
3311 SemiMonthly { days: (u8, u8), annual_special: bool },
3314 fn one_up_competitor(competitor_frequency: PublicationFrequency)
3315 -> PublicationFrequency {
3316 match competitor_frequency {
3317 PublicationFrequency::Weekly => PublicationFrequency::SemiMonthly {
3318 days: (1, 15), annual_special: false
3320 c @ PublicationFrequency::SemiMonthly{ .. } =>
3321 PublicationFrequency::SemiMonthly {
3322 annual_special: true, ..c // error: functional record update
3323 // syntax requires a struct
3329 Rewrite the expression without functional record update syntax:
3332 enum PublicationFrequency {
3334 SemiMonthly { days: (u8, u8), annual_special: bool },
3337 fn one_up_competitor(competitor_frequency: PublicationFrequency)
3338 -> PublicationFrequency {
3339 match competitor_frequency {
3340 PublicationFrequency::Weekly => PublicationFrequency::SemiMonthly {
3341 days: (1, 15), annual_special: false
3343 PublicationFrequency::SemiMonthly{ days, .. } =>
3344 PublicationFrequency::SemiMonthly {
3345 days, annual_special: true // ok!
3353 The length of the platform-intrinsic function `simd_shuffle`
3354 wasn't specified. Erroneous code example:
3356 ```compile_fail,E0439
3357 #![feature(platform_intrinsics)]
3359 extern "platform-intrinsic" {
3360 fn simd_shuffle<A,B>(a: A, b: A, c: [u32; 8]) -> B;
3361 // error: invalid `simd_shuffle`, needs length: `simd_shuffle`
3365 The `simd_shuffle` function needs the length of the array passed as
3366 last parameter in its name. Example:
3369 #![feature(platform_intrinsics)]
3371 extern "platform-intrinsic" {
3372 fn simd_shuffle8<A,B>(a: A, b: A, c: [u32; 8]) -> B;
3378 The `typeof` keyword is currently reserved but unimplemented.
3379 Erroneous code example:
3381 ```compile_fail,E0516
3383 let x: typeof(92) = 92;
3387 Try using type inference instead. Example:
3397 A non-default implementation was already made on this type so it cannot be
3398 specialized further. Erroneous code example:
3400 ```compile_fail,E0520
3401 #![feature(specialization)]
3408 impl<T> SpaceLlama for T {
3409 default fn fly(&self) {}
3413 // applies to all `Clone` T and overrides the previous impl
3414 impl<T: Clone> SpaceLlama for T {
3418 // since `i32` is clone, this conflicts with the previous implementation
3419 impl SpaceLlama for i32 {
3420 default fn fly(&self) {}
3421 // error: item `fly` is provided by an `impl` that specializes
3422 // another, but the item in the parent `impl` is not marked
3423 // `default` and so it cannot be specialized.
3427 Specialization only allows you to override `default` functions in
3430 To fix this error, you need to mark all the parent implementations as default.
3434 #![feature(specialization)]
3441 impl<T> SpaceLlama for T {
3442 default fn fly(&self) {} // This is a parent implementation.
3445 // applies to all `Clone` T; overrides the previous impl
3446 impl<T: Clone> SpaceLlama for T {
3447 default fn fly(&self) {} // This is a parent implementation but was
3448 // previously not a default one, causing the error
3451 // applies to i32, overrides the previous two impls
3452 impl SpaceLlama for i32 {
3453 fn fly(&self) {} // And now that's ok!
3459 The number of elements in an array or slice pattern differed from the number of
3460 elements in the array being matched.
3462 Example of erroneous code:
3464 ```compile_fail,E0527
3465 let r = &[1, 2, 3, 4];
3467 &[a, b] => { // error: pattern requires 2 elements but array
3469 println!("a={}, b={}", a, b);
3474 Ensure that the pattern is consistent with the size of the matched
3475 array. Additional elements can be matched with `..`:
3478 #![feature(slice_patterns)]
3480 let r = &[1, 2, 3, 4];
3482 &[a, b, ..] => { // ok!
3483 println!("a={}, b={}", a, b);
3490 An array or slice pattern required more elements than were present in the
3493 Example of erroneous code:
3495 ```compile_fail,E0528
3496 #![feature(slice_patterns)]
3500 &[a, b, c, rest..] => { // error: pattern requires at least 3
3501 // elements but array has 2
3502 println!("a={}, b={}, c={} rest={:?}", a, b, c, rest);
3507 Ensure that the matched array has at least as many elements as the pattern
3508 requires. You can match an arbitrary number of remaining elements with `..`:
3511 #![feature(slice_patterns)]
3513 let r = &[1, 2, 3, 4, 5];
3515 &[a, b, c, rest..] => { // ok!
3516 // prints `a=1, b=2, c=3 rest=[4, 5]`
3517 println!("a={}, b={}, c={} rest={:?}", a, b, c, rest);
3524 An array or slice pattern was matched against some other type.
3526 Example of erroneous code:
3528 ```compile_fail,E0529
3531 [a, b] => { // error: expected an array or slice, found `f32`
3532 println!("a={}, b={}", a, b);
3537 Ensure that the pattern and the expression being matched on are of consistent
3544 println!("a={}, b={}", a, b);
3551 The `inline` attribute was malformed.
3553 Erroneous code example:
3555 ```ignore (compile_fail not working here; see Issue #43707)
3556 #[inline()] // error: expected one argument
3557 pub fn something() {}
3562 The parenthesized `inline` attribute requires the parameter to be specified:
3576 Alternatively, a paren-less version of the attribute may be used to hint the
3577 compiler about inlining opportunity:
3584 For more information about the inline attribute, read:
3585 https://doc.rust-lang.org/reference.html#inline-attributes
3589 An unknown argument was given to the `inline` attribute.
3591 Erroneous code example:
3593 ```ignore (compile_fail not working here; see Issue #43707)
3594 #[inline(unknown)] // error: invalid argument
3595 pub fn something() {}
3600 The `inline` attribute only supports two arguments:
3605 All other arguments given to the `inline` attribute will return this error.
3609 #[inline(never)] // ok!
3610 pub fn something() {}
3615 For more information about the inline attribute, https:
3616 read://doc.rust-lang.org/reference.html#inline-attributes
3620 An unknown field was specified into an enum's structure variant.
3622 Erroneous code example:
3624 ```compile_fail,E0559
3629 let s = Field::Fool { joke: 0 };
3630 // error: struct variant `Field::Fool` has no field named `joke`
3633 Verify you didn't misspell the field's name or that the field exists. Example:
3640 let s = Field::Fool { joke: 0 }; // ok!
3645 An unknown field was specified into a structure.
3647 Erroneous code example:
3649 ```compile_fail,E0560
3654 let s = Simba { mother: 1, father: 0 };
3655 // error: structure `Simba` has no field named `father`
3658 Verify you didn't misspell the field's name or that the field exists. Example:
3666 let s = Simba { mother: 1, father: 0 }; // ok!
3671 If an impl has a generic parameter with the `#[may_dangle]` attribute, then
3672 that impl must be declared as an `unsafe impl.
3674 Erroneous code example:
3676 ```compile_fail,E0569
3677 #![feature(dropck_eyepatch)]
3680 impl<#[may_dangle] X> Drop for Foo<X> {
3681 fn drop(&mut self) { }
3685 In this example, we are asserting that the destructor for `Foo` will not
3686 access any data of type `X`, and require this assertion to be true for
3687 overall safety in our program. The compiler does not currently attempt to
3688 verify this assertion; therefore we must tag this `impl` as unsafe.
3692 The requested ABI is unsupported by the current target.
3694 The rust compiler maintains for each target a blacklist of ABIs unsupported on
3695 that target. If an ABI is present in such a list this usually means that the
3696 target / ABI combination is currently unsupported by llvm.
3698 If necessary, you can circumvent this check using custom target specifications.
3702 A return statement was found outside of a function body.
3704 Erroneous code example:
3706 ```compile_fail,E0572
3707 const FOO: u32 = return 0; // error: return statement outside of function body
3712 To fix this issue, just remove the return keyword or move the expression into a
3718 fn some_fn() -> u32 {
3729 In a `fn` type, a lifetime appears only in the return type,
3730 and not in the arguments types.
3732 Erroneous code example:
3734 ```compile_fail,E0581
3736 // Here, `'a` appears only in the return type:
3737 let x: for<'a> fn() -> &'a i32;
3741 To fix this issue, either use the lifetime in the arguments, or use
3746 // Here, `'a` appears only in the return type:
3747 let x: for<'a> fn(&'a i32) -> &'a i32;
3748 let y: fn() -> &'static i32;
3752 Note: The examples above used to be (erroneously) accepted by the
3753 compiler, but this was since corrected. See [issue #33685] for more
3756 [issue #33685]: https://github.com/rust-lang/rust/issues/33685
3760 A lifetime appears only in an associated-type binding,
3761 and not in the input types to the trait.
3763 Erroneous code example:
3765 ```compile_fail,E0582
3767 // No type can satisfy this requirement, since `'a` does not
3768 // appear in any of the input types (here, `i32`):
3769 where F: for<'a> Fn(i32) -> Option<&'a i32>
3776 To fix this issue, either use the lifetime in the inputs, or use
3780 fn bar<F, G>(t: F, u: G)
3781 where F: for<'a> Fn(&'a i32) -> Option<&'a i32>,
3782 G: Fn(i32) -> Option<&'static i32>,
3789 Note: The examples above used to be (erroneously) accepted by the
3790 compiler, but this was since corrected. See [issue #33685] for more
3793 [issue #33685]: https://github.com/rust-lang/rust/issues/33685
3797 This error occurs when a method is used on a type which doesn't implement it:
3799 Erroneous code example:
3801 ```compile_fail,E0599
3805 x.chocolate(); // error: no method named `chocolate` found for type `Mouth`
3806 // in the current scope
3811 An unary operator was used on a type which doesn't implement it.
3813 Example of erroneous code:
3815 ```compile_fail,E0600
3821 !Question::Yes; // error: cannot apply unary operator `!` to type `Question`
3824 In this case, `Question` would need to implement the `std::ops::Not` trait in
3825 order to be able to use `!` on it. Let's implement it:
3835 // We implement the `Not` trait on the enum.
3836 impl Not for Question {
3839 fn not(self) -> bool {
3841 Question::Yes => false, // If the `Answer` is `Yes`, then it
3843 Question::No => true, // And here we do the opposite.
3848 assert_eq!(!Question::Yes, false);
3849 assert_eq!(!Question::No, true);
3854 An attempt to index into a type which doesn't implement the `std::ops::Index`
3855 trait was performed.
3857 Erroneous code example:
3859 ```compile_fail,E0608
3860 0u8[2]; // error: cannot index into a value of type `u8`
3863 To be able to index into a type it needs to implement the `std::ops::Index`
3867 let v: Vec<u8> = vec![0, 1, 2, 3];
3869 // The `Vec` type implements the `Index` trait so you can do:
3870 println!("{}", v[2]);
3875 A cast to `char` was attempted on a type other than `u8`.
3877 Erroneous code example:
3879 ```compile_fail,E0604
3880 0u32 as char; // error: only `u8` can be cast as `char`, not `u32`
3883 As the error message indicates, only `u8` can be cast into `char`. Example:
3886 let c = 86u8 as char; // ok!
3890 For more information about casts, take a look at the Type cast section in
3891 [The Reference Book][1].
3893 [1]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
3897 An invalid cast was attempted.
3899 Erroneous code examples:
3901 ```compile_fail,E0605
3903 x as Vec<u8>; // error: non-primitive cast: `u8` as `std::vec::Vec<u8>`
3907 let v = 0 as *const u8; // So here, `v` is a `*const u8`.
3908 v as &u8; // error: non-primitive cast: `*const u8` as `&u8`
3911 Only primitive types can be cast into each other. Examples:
3917 let v = 0 as *const u8;
3918 v as *const i8; // ok!
3921 For more information about casts, take a look at the Type cast section in
3922 [The Reference Book][1].
3924 [1]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
3928 An incompatible cast was attempted.
3930 Erroneous code example:
3932 ```compile_fail,E0606
3933 let x = &0u8; // Here, `x` is a `&u8`.
3934 let y: u32 = x as u32; // error: casting `&u8` as `u32` is invalid
3937 When casting, keep in mind that only primitive types can be cast into each
3942 let y: u32 = *x as u32; // We dereference it first and then cast it.
3945 For more information about casts, take a look at the Type cast section in
3946 [The Reference Book][1].
3948 [1]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
3952 A cast between a thin and a fat pointer was attempted.
3954 Erroneous code example:
3956 ```compile_fail,E0607
3957 let v = 0 as *const u8;
3961 First: what are thin and fat pointers?
3963 Thin pointers are "simple" pointers: they are purely a reference to a memory
3966 Fat pointers are pointers referencing Dynamically Sized Types (also called DST).
3967 DST don't have a statically known size, therefore they can only exist behind
3968 some kind of pointers that contain additional information. Slices and trait
3969 objects are DSTs. In the case of slices, the additional information the fat
3970 pointer holds is their size.
3972 To fix this error, don't try to cast directly between thin and fat pointers.
3974 For more information about casts, take a look at the Type cast section in
3975 [The Reference Book][1].
3977 [1]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
3981 Attempted to access a non-existent field in a struct.
3983 Erroneous code example:
3985 ```compile_fail,E0609
3986 struct StructWithFields {
3990 let s = StructWithFields { x: 0 };
3991 println!("{}", s.foo); // error: no field `foo` on type `StructWithFields`
3994 To fix this error, check that you didn't misspell the field's name or that the
3995 field actually exists. Example:
3998 struct StructWithFields {
4002 let s = StructWithFields { x: 0 };
4003 println!("{}", s.x); // ok!
4008 Attempted to access a field on a primitive type.
4010 Erroneous code example:
4012 ```compile_fail,E0610
4014 println!("{}", x.foo); // error: `{integer}` is a primitive type, therefore
4015 // doesn't have fields
4018 Primitive types are the most basic types available in Rust and don't have
4019 fields. To access data via named fields, struct types are used. Example:
4022 // We declare struct called `Foo` containing two fields:
4028 // We create an instance of this struct:
4029 let variable = Foo { x: 0, y: -12 };
4030 // And we can now access its fields:
4031 println!("x: {}, y: {}", variable.x, variable.y);
4034 For more information about primitives and structs, take a look at The Book:
4035 https://doc.rust-lang.org/book/ch03-02-data-types.html
4036 https://doc.rust-lang.org/book/ch05-00-structs.html
4040 Attempted to dereference a variable which cannot be dereferenced.
4042 Erroneous code example:
4044 ```compile_fail,E0614
4046 *y; // error: type `u32` cannot be dereferenced
4049 Only types implementing `std::ops::Deref` can be dereferenced (such as `&T`).
4055 // So here, `x` is a `&u32`, so we can dereference it:
4061 Attempted to access a method like a field.
4063 Erroneous code example:
4065 ```compile_fail,E0615
4074 let f = Foo { x: 0 };
4075 f.method; // error: attempted to take value of method `method` on type `Foo`
4078 If you want to use a method, add `()` after it:
4081 # struct Foo { x: u32 }
4082 # impl Foo { fn method(&self) {} }
4083 # let f = Foo { x: 0 };
4087 However, if you wanted to access a field of a struct check that the field name
4088 is spelled correctly. Example:
4091 # struct Foo { x: u32 }
4092 # impl Foo { fn method(&self) {} }
4093 # let f = Foo { x: 0 };
4094 println!("{}", f.x);
4099 Attempted to access a private field on a struct.
4101 Erroneous code example:
4103 ```compile_fail,E0616
4106 x: u32, // So `x` is private in here.
4110 pub fn new() -> Foo { Foo { x: 0 } }
4114 let f = some_module::Foo::new();
4115 println!("{}", f.x); // error: field `x` of struct `some_module::Foo` is private
4118 If you want to access this field, you have two options:
4120 1) Set the field public:
4125 pub x: u32, // `x` is now public.
4129 pub fn new() -> Foo { Foo { x: 0 } }
4133 let f = some_module::Foo::new();
4134 println!("{}", f.x); // ok!
4137 2) Add a getter function:
4142 x: u32, // So `x` is still private in here.
4146 pub fn new() -> Foo { Foo { x: 0 } }
4148 // We create the getter function here:
4149 pub fn get_x(&self) -> &u32 { &self.x }
4153 let f = some_module::Foo::new();
4154 println!("{}", f.get_x()); // ok!
4159 Attempted to pass an invalid type of variable into a variadic function.
4161 Erroneous code example:
4163 ```compile_fail,E0617
4165 fn printf(c: *const i8, ...);
4169 printf(::std::ptr::null(), 0f32);
4170 // error: can't pass an `f32` to variadic function, cast to `c_double`
4174 Certain Rust types must be cast before passing them to a variadic function,
4175 because of arcane ABI rules dictated by the C standard. To fix the error,
4176 cast the value to the type specified by the error message (which you may need
4177 to import from `std::os::raw`).
4181 Attempted to call something which isn't a function nor a method.
4183 Erroneous code examples:
4185 ```compile_fail,E0618
4190 X::Entry(); // error: expected function, found `X::Entry`
4194 x(); // error: expected function, found `i32`
4197 Only functions and methods can be called using `()`. Example:
4200 // We declare a function:
4201 fn i_am_a_function() {}
4209 #### Note: this error code is no longer emitted by the compiler.
4210 The type-checker needed to know the type of an expression, but that type had not
4213 Erroneous code example:
4219 // Here, the type of `v` is not (yet) known, so we
4220 // cannot resolve this method call:
4221 v.to_uppercase(); // error: the type of this value must be known in
4228 Type inference typically proceeds from the top of the function to the bottom,
4229 figuring out types as it goes. In some cases -- notably method calls and
4230 overloadable operators like `*` -- the type checker may not have enough
4231 information *yet* to make progress. This can be true even if the rest of the
4232 function provides enough context (because the type-checker hasn't looked that
4233 far ahead yet). In this case, type annotations can be used to help it along.
4235 To fix this error, just specify the type of the variable. Example:
4238 let mut x: Vec<String> = vec![]; // We precise the type of the vec elements.
4241 v.to_uppercase(); // Since rustc now knows the type of the vec elements,
4242 // we can use `v`'s methods.
4250 A cast to an unsized type was attempted.
4252 Erroneous code example:
4254 ```compile_fail,E0620
4255 let x = &[1_usize, 2] as [usize]; // error: cast to unsized type: `&[usize; 2]`
4259 In Rust, some types don't have a known size at compile-time. For example, in a
4260 slice type like `[u32]`, the number of elements is not known at compile-time and
4261 hence the overall size cannot be computed. As a result, such types can only be
4262 manipulated through a reference (e.g., `&T` or `&mut T`) or other pointer-type
4263 (e.g., `Box` or `Rc`). Try casting to a reference instead:
4266 let x = &[1_usize, 2] as &[usize]; // ok!
4271 An intrinsic was declared without being a function.
4273 Erroneous code example:
4275 ```compile_fail,E0622
4276 #![feature(intrinsics)]
4277 extern "rust-intrinsic" {
4278 pub static breakpoint : unsafe extern "rust-intrinsic" fn();
4279 // error: intrinsic must be a function
4282 fn main() { unsafe { breakpoint(); } }
4285 An intrinsic is a function available for use in a given programming language
4286 whose implementation is handled specially by the compiler. In order to fix this
4287 error, just declare a function.
4291 A private item was used outside of its scope.
4293 Erroneous code example:
4295 ```compile_fail,E0624
4304 let foo = inner::Foo;
4305 foo.method(); // error: method `method` is private
4308 Two possibilities are available to solve this issue:
4310 1. Only use the item in the scope it has been defined:
4320 pub fn call_method(foo: &Foo) { // We create a public function.
4321 foo.method(); // Which calls the item.
4325 let foo = inner::Foo;
4326 inner::call_method(&foo); // And since the function is public, we can call the
4327 // method through it.
4330 2. Make the item public:
4337 pub fn method(&self) {} // It's now public.
4341 let foo = inner::Foo;
4342 foo.method(); // Ok!
4347 This error indicates that the struct, enum or enum variant must be matched
4348 non-exhaustively as it has been marked as `non_exhaustive`.
4350 When applied within a crate, downstream users of the crate will need to use the
4351 `_` pattern when matching enums and use the `..` pattern when matching structs.
4352 Downstream crates cannot match against non-exhaustive enum variants.
4354 For example, in the below example, since the enum is marked as
4355 `non_exhaustive`, it is required that downstream crates match non-exhaustively
4358 ```rust,ignore (pseudo-Rust)
4359 use std::error::Error as StdError;
4361 #[non_exhaustive] pub enum Error {
4366 impl StdError for Error {
4367 fn description(&self) -> &str {
4368 // This will not error, despite being marked as non_exhaustive, as this
4369 // enum is defined within the current crate, it can be matched
4372 Message(ref s) => s,
4373 Other => "other or unknown error",
4379 An example of matching non-exhaustively on the above enum is provided below:
4381 ```rust,ignore (pseudo-Rust)
4384 // This will not error as the non_exhaustive Error enum has been matched with a
4387 Message(ref s) => ...,
4393 Similarly, for structs, match with `..` to avoid this error.
4397 This error indicates that the struct, enum or enum variant cannot be
4398 instantiated from outside of the defining crate as it has been marked
4399 as `non_exhaustive` and as such more fields/variants may be added in
4400 future that could cause adverse side effects for this code.
4402 It is recommended that you look for a `new` function or equivalent in the
4403 crate's documentation.
4407 This error indicates that there is a mismatch between generic parameters and
4408 impl Trait parameters in a trait declaration versus its impl.
4410 ```compile_fail,E0643
4412 fn foo(&self, _: &impl Iterator);
4415 fn foo<U: Iterator>(&self, _: &U) { } // error method `foo` has incompatible
4416 // signature for trait
4422 It is not possible to define `main` with a where clause.
4423 Erroneous code example:
4425 ```compile_fail,E0646
4426 fn main() where i32: Copy { // error: main function is not allowed to have
4433 It is not possible to define `start` with a where clause.
4434 Erroneous code example:
4436 ```compile_fail,E0647
4440 fn start(_: isize, _: *const *const u8) -> isize where (): Copy {
4441 //^ error: start function is not allowed to have a where clause
4448 `export_name` attributes may not contain null characters (`\0`).
4450 ```compile_fail,E0648
4451 #[export_name="\0foo"] // error: `export_name` may not contain null characters
4457 This error indicates that the numeric value for the method being passed exists
4458 but the type of the numeric value or binding could not be identified.
4460 The error happens on numeric literals:
4462 ```compile_fail,E0689
4466 and on numeric bindings without an identified concrete type:
4468 ```compile_fail,E0689
4470 x.neg(); // same error as above
4473 Because of this, you must give the numeric literal or binding a type:
4478 let _ = 2.0_f32.neg();
4481 let _ = (2.0 as f32).neg();
4486 A struct with the representation hint `repr(transparent)` had zero or more than
4487 on fields that were not guaranteed to be zero-sized.
4489 Erroneous code example:
4491 ```compile_fail,E0690
4492 #[repr(transparent)]
4493 struct LengthWithUnit<U> { // error: transparent struct needs exactly one
4494 value: f32, // non-zero-sized field, but has 2
4499 Because transparent structs are represented exactly like one of their fields at
4500 run time, said field must be uniquely determined. If there is no field, or if
4501 there are multiple fields, it is not clear how the struct should be represented.
4502 Note that fields of zero-typed types (e.g., `PhantomData`) can also exist
4503 alongside the field that contains the actual data, they do not count for this
4504 error. When generic types are involved (as in the above example), an error is
4505 reported because the type parameter could be non-zero-sized.
4507 To combine `repr(transparent)` with type parameters, `PhantomData` may be
4511 use std::marker::PhantomData;
4513 #[repr(transparent)]
4514 struct LengthWithUnit<U> {
4516 unit: PhantomData<U>,
4522 A struct with the `repr(transparent)` representation hint contains a zero-sized
4523 field that requires non-trivial alignment.
4525 Erroneous code example:
4527 ```compile_fail,E0691
4528 #![feature(repr_align)]
4531 struct ForceAlign32;
4533 #[repr(transparent)]
4534 struct Wrapper(f32, ForceAlign32); // error: zero-sized field in transparent
4535 // struct has alignment larger than 1
4538 A transparent struct is supposed to be represented exactly like the piece of
4539 data it contains. Zero-sized fields with different alignment requirements
4540 potentially conflict with this property. In the example above, `Wrapper` would
4541 have to be aligned to 32 bytes even though `f32` has a smaller alignment
4544 Consider removing the over-aligned zero-sized field:
4547 #[repr(transparent)]
4548 struct Wrapper(f32);
4551 Alternatively, `PhantomData<T>` has alignment 1 for all `T`, so you can use it
4552 if you need to keep the field for some reason:
4555 #![feature(repr_align)]
4557 use std::marker::PhantomData;
4560 struct ForceAlign32;
4562 #[repr(transparent)]
4563 struct Wrapper(f32, PhantomData<ForceAlign32>);
4566 Note that empty arrays `[T; 0]` have the same alignment requirement as the
4567 element type `T`. Also note that the error is conservatively reported even when
4568 the alignment of the zero-sized type is less than or equal to the data field's
4574 A method was called on a raw pointer whose inner type wasn't completely known.
4576 For example, you may have done something like:
4579 # #![deny(warnings)]
4581 let bar = foo as *const _;
4587 Here, the type of `bar` isn't known; it could be a pointer to anything. Instead,
4588 specify a type for the pointer (preferably something that makes sense for the
4589 thing you're pointing to):
4593 let bar = foo as *const i32;
4599 Even though `is_null()` exists as a method on any raw pointer, Rust shows this
4600 error because Rust allows for `self` to have arbitrary types (behind the
4601 arbitrary_self_types feature flag).
4603 This means that someone can specify such a function:
4605 ```ignore (cannot-doctest-feature-doesnt-exist-yet)
4607 fn is_null(self: *const Self) -> bool {
4608 // do something else
4613 and now when you call `.is_null()` on a raw pointer to `Foo`, there's ambiguity.
4615 Given that we don't know what type the pointer is, and there's potential
4616 ambiguity for some types, we disallow calling methods on raw pointers when
4617 the type is unknown.
4621 A `#[marker]` trait contained an associated item.
4623 The items of marker traits cannot be overridden, so there's no need to have them
4624 when they cannot be changed per-type anyway. If you wanted them for ergonomic
4625 reasons, consider making an extension trait instead.
4629 An `impl` for a `#[marker]` trait tried to override an associated item.
4631 Because marker traits are allowed to have multiple implementations for the same
4632 type, it's not allowed to override anything in those implementations, as it
4633 would be ambiguous which override should actually be used.
4638 An `impl Trait` type expands to a recursive type.
4640 An `impl Trait` type must be expandable to a concrete type that contains no
4641 `impl Trait` types. For example the following example tries to create an
4642 `impl Trait` type `T` that is equal to `[T, T]`:
4644 ```compile_fail,E0720
4645 fn make_recursive_type() -> impl Sized {
4646 [make_recursive_type(), make_recursive_type()]
4653 register_diagnostics! {
4654 // E0035, merged into E0087/E0089
4655 // E0036, merged into E0087/E0089
4661 // E0122, // bounds in type aliases are ignored, turned into proper lint
4666 // E0159, // use of trait `{}` as struct constructor
4667 // E0163, // merged into E0071
4670 // E0172, // non-trait found in a type sum, moved to resolve
4671 // E0173, // manual implementations of unboxed closure traits are experimental
4673 // E0182, // merged into E0229
4675 // E0187, // can't infer the kind of the closure
4676 // E0188, // can not cast an immutable reference to a mutable pointer
4677 // E0189, // deprecated: can only cast a boxed pointer to a boxed object
4678 // E0190, // deprecated: can only cast a &-pointer to an &-object
4679 // E0196, // cannot determine a type for this closure
4680 E0203, // type parameter has more than one relaxed default bound,
4681 // and only one is supported
4683 // E0209, // builtin traits can only be implemented on structs or enums
4684 E0212, // cannot extract an associated type from a higher-ranked trait bound
4685 // E0213, // associated types are not accepted in this context
4686 // E0215, // angle-bracket notation is not stable with `Fn`
4687 // E0216, // parenthetical notation is only stable with `Fn`
4688 // E0217, // ambiguous associated type, defined in multiple supertraits
4689 // E0218, // no associated type defined
4690 // E0219, // associated type defined in higher-ranked supertrait
4691 // E0222, // Error code E0045 (variadic function must have C or cdecl calling
4692 // convention) duplicate
4693 E0224, // at least one non-builtin train is required for an object type
4694 E0227, // ambiguous lifetime bound, explicit lifetime bound required
4695 E0228, // explicit lifetime bound required
4698 // E0235, // structure constructor specifies a structure of type but
4699 // E0236, // no lang item for range syntax
4700 // E0237, // no lang item for range syntax
4701 // E0238, // parenthesized parameters may only be used with a trait
4702 // E0239, // `next` method of `Iterator` trait has unexpected type
4706 // E0245, // not a trait
4707 // E0246, // invalid recursive type
4709 // E0248, // value used as a type, now reported earlier during resolution as E0412
4711 E0307, // invalid method `self` type
4712 // E0319, // trait impls for defaulted traits allowed just for structs/enums
4713 // E0372, // coherence not object safe
4714 E0377, // the trait `CoerceUnsized` may only be implemented for a coercion
4715 // between structures with the same definition
4716 // E0558, // replaced with a generic attribute input check
4717 E0533, // `{}` does not name a unit variant, unit struct or a constant
4718 // E0563, // cannot determine a type for this `impl Trait`: {} // removed in 6383de15
4719 E0564, // only named lifetimes are allowed in `impl Trait`,
4720 // but `{}` was found in the type `{}`
4721 E0587, // type has conflicting packed and align representation hints
4722 E0588, // packed type cannot transitively contain a `[repr(align)]` type
4723 E0592, // duplicate definitions with name `{}`
4724 // E0611, // merged into E0616
4725 // E0612, // merged into E0609
4726 // E0613, // Removed (merged with E0609)
4727 E0627, // yield statement outside of generator literal
4728 E0632, // cannot provide explicit type parameters when `impl Trait` is used in
4729 // argument position.
4730 E0634, // type has conflicting packed representaton hints
4731 E0640, // infer outlives requirements
4732 E0641, // cannot cast to/from a pointer with an unknown kind
4733 E0645, // trait aliases not finished
4734 E0719, // duplicate values for associated type binding
4735 E0722, // Malformed #[optimize] attribute
4736 E0724, // `#[ffi_returns_twice]` is only allowed in foreign functions