1 // ignore-tidy-filelength
3 register_long_diagnostics! {
6 A pattern used to match against an enum variant must provide a sub-pattern for
7 each field of the enum variant. This error indicates that a pattern attempted to
8 extract an incorrect number of fields from a variant.
12 Apple(String, String),
17 Here the `Apple` variant has two fields, and should be matched against like so:
21 Apple(String, String),
25 let x = Fruit::Apple(String::new(), String::new());
29 Fruit::Apple(a, b) => {},
34 Matching with the wrong number of fields has no sensible interpretation:
38 Apple(String, String),
42 let x = Fruit::Apple(String::new(), String::new());
46 Fruit::Apple(a) => {},
47 Fruit::Apple(a, b, c) => {},
51 Check how many fields the enum was declared with and ensure that your pattern
56 Each field of a struct can only be bound once in a pattern. Erroneous code
66 let x = Foo { a:1, b:2 };
68 let Foo { a: x, a: y } = x;
69 // error: field `a` bound multiple times in the pattern
73 Each occurrence of a field name binds the value of that field, so to fix this
74 error you will have to remove or alter the duplicate uses of the field name.
75 Perhaps you misspelled another field name? Example:
84 let x = Foo { a:1, b:2 };
86 let Foo { a: x, b: y } = x; // ok!
92 This error indicates that a struct pattern attempted to extract a non-existent
93 field from a struct. Struct fields are identified by the name used before the
94 colon `:` so struct patterns should resemble the declaration of the struct type
104 let thing = Thing { x: 1, y: 2 };
107 Thing { x: xfield, y: yfield } => {}
111 If you are using shorthand field patterns but want to refer to the struct field
112 by a different name, you should rename it explicitly.
116 ```compile_fail,E0026
122 let thing = Thing { x: 0, y: 0 };
137 let thing = Thing { x: 0, y: 0 };
140 Thing { x, y: z } => {}
146 This error indicates that a pattern for a struct fails to specify a sub-pattern
147 for every one of the struct's fields. Ensure that each field from the struct's
148 definition is mentioned in the pattern, or use `..` to ignore unwanted fields.
152 ```compile_fail,E0027
158 let d = Dog { name: "Rusty".to_string(), age: 8 };
160 // This is incorrect.
166 This is correct (explicit):
174 let d = Dog { name: "Rusty".to_string(), age: 8 };
177 Dog { name: ref n, age: x } => {}
180 // This is also correct (ignore unused fields).
182 Dog { age: x, .. } => {}
188 In a match expression, only numbers and characters can be matched against a
189 range. This is because the compiler checks that the range is non-empty at
190 compile-time, and is unable to evaluate arbitrary comparison functions. If you
191 want to capture values of an orderable type between two end-points, you can use
194 ```compile_fail,E0029
195 let string = "salutations !";
197 // The ordering relation for strings can't be evaluated at compile time,
198 // so this doesn't work:
200 "hello" ..= "world" => {}
204 // This is a more general version, using a guard:
206 s if s >= "hello" && s <= "world" => {}
213 This error indicates that a pointer to a trait type cannot be implicitly
214 dereferenced by a pattern. Every trait defines a type, but because the
215 size of trait implementors isn't fixed, this type has no compile-time size.
216 Therefore, all accesses to trait types must be through pointers. If you
217 encounter this error you should try to avoid dereferencing the pointer.
219 ```compile_fail,E0033
220 # trait SomeTrait { fn method_one(&self){} fn method_two(&self){} }
221 # impl<T> SomeTrait for T {}
222 let trait_obj: &SomeTrait = &"some_value";
224 // This tries to implicitly dereference to create an unsized local variable.
225 let &invalid = trait_obj;
227 // You can call methods without binding to the value being pointed at.
228 trait_obj.method_one();
229 trait_obj.method_two();
232 You can read more about trait objects in the [Trait Objects] section of the
235 [Trait Objects]: https://doc.rust-lang.org/reference/types.html#trait-objects
239 The compiler doesn't know what method to call because more than one method
240 has the same prototype. Erroneous code example:
242 ```compile_fail,E0034
253 impl Trait1 for Test { fn foo() {} }
254 impl Trait2 for Test { fn foo() {} }
257 Test::foo() // error, which foo() to call?
261 To avoid this error, you have to keep only one of them and remove the others.
262 So let's take our example and fix it:
271 impl Trait1 for Test { fn foo() {} }
274 Test::foo() // and now that's good!
278 However, a better solution would be using fully explicit naming of type and
292 impl Trait1 for Test { fn foo() {} }
293 impl Trait2 for Test { fn foo() {} }
296 <Test as Trait1>::foo()
313 impl F for X { fn m(&self) { println!("I am F"); } }
314 impl G for X { fn m(&self) { println!("I am G"); } }
319 F::m(&f); // it displays "I am F"
320 G::m(&f); // it displays "I am G"
326 It is not allowed to manually call destructors in Rust. It is also not
327 necessary to do this since `drop` is called automatically whenever a value goes
330 Here's an example of this error:
332 ```compile_fail,E0040
344 let mut x = Foo { x: -7 };
345 x.drop(); // error: explicit use of destructor method
351 You can't use type or const parameters on foreign items.
352 Example of erroneous code:
354 ```compile_fail,E0044
355 extern { fn some_func<T>(x: T); }
358 To fix this, replace the generic parameter with the specializations that you
362 extern { fn some_func_i32(x: i32); }
363 extern { fn some_func_i64(x: i64); }
368 Rust only supports variadic parameters for interoperability with C code in its
369 FFI. As such, variadic parameters can only be used with functions which are
370 using the C ABI. Examples of erroneous code:
373 #![feature(unboxed_closures)]
375 extern "rust-call" { fn foo(x: u8, ...); }
379 fn foo(x: u8, ...) {}
382 To fix such code, put them in an extern "C" block:
392 Items are missing in a trait implementation. Erroneous code example:
394 ```compile_fail,E0046
402 // error: not all trait items implemented, missing: `foo`
405 When trying to make some type implement a trait `Foo`, you must, at minimum,
406 provide implementations for all of `Foo`'s required methods (meaning the
407 methods that do not have default implementations), as well as any required
408 trait items like associated types or constants. Example:
424 This error indicates that an attempted implementation of a trait method
425 has the wrong number of type or const parameters.
427 For example, the trait below has a method `foo` with a type parameter `T`,
428 but the implementation of `foo` for the type `Bar` is missing this parameter:
430 ```compile_fail,E0049
432 fn foo<T: Default>(x: T) -> Self;
437 // error: method `foo` has 0 type parameters but its trait declaration has 1
440 fn foo(x: bool) -> Self { Bar }
446 This error indicates that an attempted implementation of a trait method
447 has the wrong number of function parameters.
449 For example, the trait below has a method `foo` with two function parameters
450 (`&self` and `u8`), but the implementation of `foo` for the type `Bar` omits
453 ```compile_fail,E0050
455 fn foo(&self, x: u8) -> bool;
460 // error: method `foo` has 1 parameter but the declaration in trait `Foo::foo`
463 fn foo(&self) -> bool { true }
469 The parameters of any trait method must match between a trait implementation
470 and the trait definition.
472 Here are a couple examples of this error:
474 ```compile_fail,E0053
483 // error, expected u16, found i16
486 // error, types differ in mutability
487 fn bar(&mut self) { }
493 It is not allowed to cast to a bool. If you are trying to cast a numeric type
494 to a bool, you can compare it with zero instead:
496 ```compile_fail,E0054
499 // Not allowed, won't compile
500 let x_is_nonzero = x as bool;
507 let x_is_nonzero = x != 0;
512 During a method call, a value is automatically dereferenced as many times as
513 needed to make the value's type match the method's receiver. The catch is that
514 the compiler will only attempt to dereference a number of times up to the
515 recursion limit (which can be set via the `recursion_limit` attribute).
517 For a somewhat artificial example:
519 ```compile_fail,E0055
520 #![recursion_limit="5"]
530 let ref_foo = &&&&&Foo;
532 // error, reached the recursion limit while auto-dereferencing `&&&&&Foo`
537 One fix may be to increase the recursion limit. Note that it is possible to
538 create an infinite recursion of dereferencing, in which case the only fix is to
539 somehow break the recursion.
543 When invoking closures or other implementations of the function traits `Fn`,
544 `FnMut` or `FnOnce` using call notation, the number of parameters passed to the
545 function must match its definition.
547 An example using a closure:
549 ```compile_fail,E0057
551 let a = f(); // invalid, too few parameters
552 let b = f(4); // this works!
553 let c = f(2, 3); // invalid, too many parameters
556 A generic function must be treated similarly:
559 fn foo<F: Fn()>(f: F) {
560 f(); // this is valid, but f(3) would not work
566 The built-in function traits are generic over a tuple of the function arguments.
567 If one uses angle-bracket notation (`Fn<(T,), Output=U>`) instead of parentheses
568 (`Fn(T) -> U`) to denote the function trait, the type parameter should be a
569 tuple. Otherwise function call notation cannot be used and the trait will not be
570 implemented by closures.
572 The most likely source of this error is using angle-bracket notation without
573 wrapping the function argument type into a tuple, for example:
575 ```compile_fail,E0059
576 #![feature(unboxed_closures)]
578 fn foo<F: Fn<i32>>(f: F) -> F::Output { f(3) }
581 It can be fixed by adjusting the trait bound like this:
584 #![feature(unboxed_closures)]
586 fn foo<F: Fn<(i32,)>>(f: F) -> F::Output { f(3) }
589 Note that `(T,)` always denotes the type of a 1-tuple containing an element of
590 type `T`. The comma is necessary for syntactic disambiguation.
594 External C functions are allowed to be variadic. However, a variadic function
595 takes a minimum number of arguments. For example, consider C's variadic `printf`
599 use std::os::raw::{c_char, c_int};
602 fn printf(_: *const c_char, ...) -> c_int;
606 Using this declaration, it must be called with at least one argument, so
607 simply calling `printf()` is invalid. But the following uses are allowed:
610 # #![feature(static_nobundle)]
611 # use std::os::raw::{c_char, c_int};
612 # #[cfg_attr(all(windows, target_env = "msvc"),
613 # link(name = "legacy_stdio_definitions", kind = "static-nobundle"))]
614 # extern "C" { fn printf(_: *const c_char, ...) -> c_int; }
617 use std::ffi::CString;
619 let fmt = CString::new("test\n").unwrap();
620 printf(fmt.as_ptr());
622 let fmt = CString::new("number = %d\n").unwrap();
623 printf(fmt.as_ptr(), 3);
625 let fmt = CString::new("%d, %d\n").unwrap();
626 printf(fmt.as_ptr(), 10, 5);
631 // ^ Note: On MSVC 2015, the `printf` function is "inlined" in the C code, and
632 // the C runtime does not contain the `printf` definition. This leads to linker
633 // error from the doc test (issue #42830).
634 // This can be fixed by linking to the static library
635 // `legacy_stdio_definitions.lib` (see https://stackoverflow.com/a/36504365/).
636 // If this compatibility library is removed in the future, consider changing
637 // `printf` in this example to another well-known variadic function.
640 The number of arguments passed to a function must match the number of arguments
641 specified in the function signature.
643 For example, a function like:
646 fn f(a: u16, b: &str) {}
649 Must always be called with exactly two arguments, e.g., `f(2, "test")`.
651 Note that Rust does not have a notion of optional function arguments or
652 variadic functions (except for its C-FFI).
656 This error indicates that during an attempt to build a struct or struct-like
657 enum variant, one of the fields was specified more than once. Erroneous code
660 ```compile_fail,E0062
668 x: 0, // error: field `x` specified more than once
673 Each field should be specified exactly one time. Example:
681 let x = Foo { x: 0 }; // ok!
687 This error indicates that during an attempt to build a struct or struct-like
688 enum variant, one of the fields was not provided. Erroneous code example:
690 ```compile_fail,E0063
697 let x = Foo { x: 0 }; // error: missing field: `y`
701 Each field should be specified exactly once. Example:
710 let x = Foo { x: 0, y: 0 }; // ok!
716 The left-hand side of a compound assignment expression must be a place
717 expression. A place expression represents a memory location and includes
718 item paths (ie, namespaced variables), dereferences, indexing expressions,
719 and field references.
721 Let's start with some erroneous code examples:
723 ```compile_fail,E0067
724 use std::collections::LinkedList;
726 // Bad: assignment to non-place expression
727 LinkedList::new() += 1;
731 fn some_func(i: &mut i32) {
732 i += 12; // Error : '+=' operation cannot be applied on a reference !
736 And now some working examples:
745 fn some_func(i: &mut i32) {
752 The compiler found a function whose body contains a `return;` statement but
753 whose return type is not `()`. An example of this is:
755 ```compile_fail,E0069
762 Since `return;` is just like `return ();`, there is a mismatch between the
763 function's return type and the value being returned.
767 The left-hand side of an assignment operator must be a place expression. A
768 place expression represents a memory location and can be a variable (with
769 optional namespacing), a dereference, an indexing expression or a field
772 More details can be found in the [Expressions] section of the Reference.
774 [Expressions]: https://doc.rust-lang.org/reference/expressions.html#places-rvalues-and-temporaries
776 Now, we can go further. Here are some erroneous code examples:
778 ```compile_fail,E0070
784 const SOME_CONST : i32 = 12;
786 fn some_other_func() {}
789 SOME_CONST = 14; // error : a constant value cannot be changed!
790 1 = 3; // error : 1 isn't a valid place!
791 some_other_func() = 4; // error : we can't assign value to a function!
792 SomeStruct.x = 12; // error : SomeStruct a structure name but it is used
797 And now let's give working examples:
804 let mut s = SomeStruct {x: 0, y: 0};
806 s.x = 3; // that's good !
810 fn some_func(x: &mut i32) {
811 *x = 12; // that's good !
817 You tried to use structure-literal syntax to create an item that is
818 not a structure or enum variant.
820 Example of erroneous code:
822 ```compile_fail,E0071
824 let t = U32 { value: 4 }; // error: expected struct, variant or union type,
825 // found builtin type `u32`
828 To fix this, ensure that the name was correctly spelled, and that
829 the correct form of initializer was used.
831 For example, the code above can be fixed to:
839 let u = Foo::FirstValue(0i32);
847 #### Note: this error code is no longer emitted by the compiler.
849 You cannot define a struct (or enum) `Foo` that requires an instance of `Foo`
850 in order to make a new `Foo` value. This is because there would be no way a
851 first instance of `Foo` could be made to initialize another instance!
853 Here's an example of a struct that has this problem:
856 struct Foo { x: Box<Foo> } // error
859 One fix is to use `Option`, like so:
862 struct Foo { x: Option<Box<Foo>> }
865 Now it's possible to create at least one instance of `Foo`: `Foo { x: None }`.
869 #### Note: this error code is no longer emitted by the compiler.
871 When using the `#[simd]` attribute on a tuple struct, the components of the
872 tuple struct must all be of a concrete, nongeneric type so the compiler can
873 reason about how to use SIMD with them. This error will occur if the types
876 This will cause an error:
879 #![feature(repr_simd)]
882 struct Bad<T>(T, T, T);
888 #![feature(repr_simd)]
891 struct Good(u32, u32, u32);
896 The `#[simd]` attribute can only be applied to non empty tuple structs, because
897 it doesn't make sense to try to use SIMD operations when there are no values to
900 This will cause an error:
902 ```compile_fail,E0075
903 #![feature(repr_simd)]
912 #![feature(repr_simd)]
920 When using the `#[simd]` attribute to automatically use SIMD operations in tuple
921 struct, the types in the struct must all be of the same type, or the compiler
922 will trigger this error.
924 This will cause an error:
926 ```compile_fail,E0076
927 #![feature(repr_simd)]
930 struct Bad(u16, u32, u32);
936 #![feature(repr_simd)]
939 struct Good(u32, u32, u32);
944 When using the `#[simd]` attribute on a tuple struct, the elements in the tuple
945 must be machine types so SIMD operations can be applied to them.
947 This will cause an error:
949 ```compile_fail,E0077
950 #![feature(repr_simd)]
959 #![feature(repr_simd)]
962 struct Good(u32, u32, u32);
967 Enum discriminants are used to differentiate enum variants stored in memory.
968 This error indicates that the same value was used for two or more variants,
969 making them impossible to tell apart.
971 ```compile_fail,E0081
989 Note that variants without a manually specified discriminant are numbered from
990 top to bottom starting from 0, so clashes can occur with seemingly unrelated
993 ```compile_fail,E0081
1000 Here `X` will have already been specified the discriminant 0 by the time `Y` is
1001 encountered, so a conflict occurs.
1005 An unsupported representation was attempted on a zero-variant enum.
1007 Erroneous code example:
1009 ```compile_fail,E0084
1011 enum NightsWatch {} // error: unsupported representation for zero-variant enum
1014 It is impossible to define an integer type to be used to represent zero-variant
1015 enum values because there are no zero-variant enum values. There is no way to
1016 construct an instance of the following type using only safe code. So you have
1017 two solutions. Either you add variants in your enum:
1027 or you remove the integer represention of your enum:
1034 // FIXME(const_generics:docs): example of inferring const parameter.
1036 #### Note: this error code is no longer emitted by the compiler.
1038 Too many type arguments were supplied for a function. For example:
1040 ```compile_fail,E0107
1044 foo::<f64, bool>(); // error: wrong number of type arguments:
1045 // expected 1, found 2
1049 The number of supplied arguments must exactly match the number of defined type
1054 #### Note: this error code is no longer emitted by the compiler.
1056 You gave too many lifetime arguments. Erroneous code example:
1058 ```compile_fail,E0107
1062 f::<'static>() // error: wrong number of lifetime arguments:
1063 // expected 0, found 1
1067 Please check you give the right number of lifetime arguments. Example:
1077 It's also important to note that the Rust compiler can generally
1078 determine the lifetime by itself. Example:
1086 // it can be written like this
1087 fn get_value<'a>(&'a self) -> &'a str { &self.value }
1088 // but the compiler works fine with this too:
1089 fn without_lifetime(&self) -> &str { &self.value }
1093 let f = Foo { value: "hello".to_owned() };
1095 println!("{}", f.get_value());
1096 println!("{}", f.without_lifetime());
1102 #### Note: this error code is no longer emitted by the compiler.
1104 Too few type arguments were supplied for a function. For example:
1106 ```compile_fail,E0107
1110 foo::<f64>(); // error: wrong number of type arguments: expected 2, found 1
1114 Note that if a function takes multiple type arguments but you want the compiler
1115 to infer some of them, you can use type placeholders:
1117 ```compile_fail,E0107
1118 fn foo<T, U>(x: T) {}
1122 foo::<f64>(x); // error: wrong number of type arguments:
1123 // expected 2, found 1
1124 foo::<_, f64>(x); // same as `foo::<bool, f64>(x)`
1130 #### Note: this error code is no longer emitted by the compiler.
1132 You gave too few lifetime arguments. Example:
1134 ```compile_fail,E0107
1135 fn foo<'a: 'b, 'b: 'a>() {}
1138 foo::<'static>(); // error: wrong number of lifetime arguments:
1139 // expected 2, found 1
1143 Please check you give the right number of lifetime arguments. Example:
1146 fn foo<'a: 'b, 'b: 'a>() {}
1149 foo::<'static, 'static>();
1155 You gave an unnecessary type or const parameter in a type alias. Erroneous
1158 ```compile_fail,E0091
1159 type Foo<T> = u32; // error: type parameter `T` is unused
1161 type Foo<A,B> = Box<A>; // error: type parameter `B` is unused
1164 Please check you didn't write too many parameters. Example:
1167 type Foo = u32; // ok!
1168 type Foo2<A> = Box<A>; // ok!
1173 You tried to declare an undefined atomic operation function.
1174 Erroneous code example:
1176 ```compile_fail,E0092
1177 #![feature(intrinsics)]
1179 extern "rust-intrinsic" {
1180 fn atomic_foo(); // error: unrecognized atomic operation
1185 Please check you didn't make a mistake in the function's name. All intrinsic
1186 functions are defined in librustc_codegen_llvm/intrinsic.rs and in
1187 libcore/intrinsics.rs in the Rust source code. Example:
1190 #![feature(intrinsics)]
1192 extern "rust-intrinsic" {
1193 fn atomic_fence(); // ok!
1199 You declared an unknown intrinsic function. Erroneous code example:
1201 ```compile_fail,E0093
1202 #![feature(intrinsics)]
1204 extern "rust-intrinsic" {
1205 fn foo(); // error: unrecognized intrinsic function: `foo`
1215 Please check you didn't make a mistake in the function's name. All intrinsic
1216 functions are defined in librustc_codegen_llvm/intrinsic.rs and in
1217 libcore/intrinsics.rs in the Rust source code. Example:
1220 #![feature(intrinsics)]
1222 extern "rust-intrinsic" {
1223 fn atomic_fence(); // ok!
1235 You gave an invalid number of type parameters to an intrinsic function.
1236 Erroneous code example:
1238 ```compile_fail,E0094
1239 #![feature(intrinsics)]
1241 extern "rust-intrinsic" {
1242 fn size_of<T, U>() -> usize; // error: intrinsic has wrong number
1243 // of type parameters
1247 Please check that you provided the right number of type parameters
1248 and verify with the function declaration in the Rust source code.
1252 #![feature(intrinsics)]
1254 extern "rust-intrinsic" {
1255 fn size_of<T>() -> usize; // ok!
1261 This error means that an incorrect number of generic arguments were provided:
1263 ```compile_fail,E0107
1264 struct Foo<T> { x: T }
1266 struct Bar { x: Foo } // error: wrong number of type arguments:
1267 // expected 1, found 0
1268 struct Baz<S, T> { x: Foo<S, T> } // error: wrong number of type arguments:
1269 // expected 1, found 2
1271 fn foo<T, U>(x: T, y: U) {}
1275 foo::<bool>(x); // error: wrong number of type arguments:
1276 // expected 2, found 1
1277 foo::<bool, i32, i32>(x, 2, 4); // error: wrong number of type arguments:
1278 // expected 2, found 3
1284 f::<'static>(); // error: wrong number of lifetime arguments:
1285 // expected 0, found 1
1292 You tried to provide a generic argument to a type which doesn't need it.
1293 Erroneous code example:
1295 ```compile_fail,E0109
1296 type X = u32<i32>; // error: type arguments are not allowed for this type
1297 type Y = bool<'static>; // error: lifetime parameters are not allowed on
1301 Check that you used the correct argument and that the definition is correct.
1306 type X = u32; // ok!
1307 type Y = bool; // ok!
1310 Note that generic arguments for enum variant constructors go after the variant,
1311 not after the enum. For example, you would write `Option::None::<u32>`,
1312 rather than `Option::<u32>::None`.
1316 #### Note: this error code is no longer emitted by the compiler.
1318 You tried to provide a lifetime to a type which doesn't need it.
1319 See `E0109` for more details.
1323 You can only define an inherent implementation for a type in the same crate
1324 where the type was defined. For example, an `impl` block as below is not allowed
1325 since `Vec` is defined in the standard library:
1327 ```compile_fail,E0116
1328 impl Vec<u8> { } // error
1331 To fix this problem, you can do either of these things:
1333 - define a trait that has the desired associated functions/types/constants and
1334 implement the trait for the type in question
1335 - define a new type wrapping the type and define an implementation on the new
1338 Note that using the `type` keyword does not work here because `type` only
1339 introduces a type alias:
1341 ```compile_fail,E0116
1342 type Bytes = Vec<u8>;
1344 impl Bytes { } // error, same as above
1349 This error indicates a violation of one of Rust's orphan rules for trait
1350 implementations. The rule prohibits any implementation of a foreign trait (a
1351 trait defined in another crate) where
1353 - the type that is implementing the trait is foreign
1354 - all of the parameters being passed to the trait (if there are any) are also
1357 Here's one example of this error:
1359 ```compile_fail,E0117
1360 impl Drop for u32 {}
1363 To avoid this kind of error, ensure that at least one local type is referenced
1367 pub struct Foo; // you define your type in your crate
1369 impl Drop for Foo { // and you can implement the trait on it!
1370 // code of trait implementation here
1371 # fn drop(&mut self) { }
1374 impl From<Foo> for i32 { // or you use a type from your crate as
1376 fn from(i: Foo) -> i32 {
1382 Alternatively, define a trait locally and implement that instead:
1386 fn get(&self) -> usize;
1390 fn get(&self) -> usize { 0 }
1394 For information on the design of the orphan rules, see [RFC 1023].
1396 [RFC 1023]: https://github.com/rust-lang/rfcs/blob/master/text/1023-rebalancing-coherence.md
1400 You're trying to write an inherent implementation for something which isn't a
1401 struct nor an enum. Erroneous code example:
1403 ```compile_fail,E0118
1404 impl (u8, u8) { // error: no base type found for inherent implementation
1405 fn get_state(&self) -> String {
1411 To fix this error, please implement a trait on the type or wrap it in a struct.
1415 // we create a trait here
1416 trait LiveLongAndProsper {
1417 fn get_state(&self) -> String;
1420 // and now you can implement it on (u8, u8)
1421 impl LiveLongAndProsper for (u8, u8) {
1422 fn get_state(&self) -> String {
1423 "He's dead, Jim!".to_owned()
1428 Alternatively, you can create a newtype. A newtype is a wrapping tuple-struct.
1429 For example, `NewType` is a newtype over `Foo` in `struct NewType(Foo)`.
1433 struct TypeWrapper((u8, u8));
1436 fn get_state(&self) -> String {
1437 "Fascinating!".to_owned()
1444 An attempt was made to implement Drop on a trait, which is not allowed: only
1445 structs and enums can implement Drop. An example causing this error:
1447 ```compile_fail,E0120
1450 impl Drop for MyTrait {
1451 fn drop(&mut self) {}
1455 A workaround for this problem is to wrap the trait up in a struct, and implement
1456 Drop on that. An example is shown below:
1460 struct MyWrapper<T: MyTrait> { foo: T }
1462 impl <T: MyTrait> Drop for MyWrapper<T> {
1463 fn drop(&mut self) {}
1468 Alternatively, wrapping trait objects requires something like the following:
1473 //or Box<MyTrait>, if you wanted an owned trait object
1474 struct MyWrapper<'a> { foo: &'a MyTrait }
1476 impl <'a> Drop for MyWrapper<'a> {
1477 fn drop(&mut self) {}
1483 In order to be consistent with Rust's lack of global type inference,
1484 type and const placeholders are disallowed by design in item signatures.
1486 Examples of this error include:
1488 ```compile_fail,E0121
1489 fn foo() -> _ { 5 } // error, explicitly write out the return type instead
1491 static BAR: _ = "test"; // error, explicitly write out the type instead
1496 You declared two fields of a struct with the same name. Erroneous code
1499 ```compile_fail,E0124
1502 field1: i32, // error: field is already declared
1506 Please verify that the field names have been correctly spelled. Example:
1517 It is not possible to define `main` with generic parameters.
1518 When `main` is present, it must take no arguments and return `()`.
1519 Erroneous code example:
1521 ```compile_fail,E0131
1522 fn main<T>() { // error: main function is not allowed to have generic parameters
1528 A function with the `start` attribute was declared with type parameters.
1530 Erroneous code example:
1532 ```compile_fail,E0132
1539 It is not possible to declare type parameters on a function that has the `start`
1540 attribute. Such a function must have the following type signature (for more
1541 information, view [the unstable book][1]):
1543 [1]: https://doc.rust-lang.org/unstable-book/language-features/lang-items.html#writing-an-executable-without-stdlib
1547 fn(isize, *const *const u8) -> isize;
1556 fn my_start(argc: isize, argv: *const *const u8) -> isize {
1563 This error means that an attempt was made to match a struct type enum
1564 variant as a non-struct type:
1566 ```compile_fail,E0164
1567 enum Foo { B { i: u32 } }
1569 fn bar(foo: Foo) -> u32 {
1571 Foo::B(i) => i, // error E0164
1576 Try using `{}` instead:
1579 enum Foo { B { i: u32 } }
1581 fn bar(foo: Foo) -> u32 {
1590 Explicitly implementing both Drop and Copy for a type is currently disallowed.
1591 This feature can make some sense in theory, but the current implementation is
1592 incorrect and can lead to memory unsafety (see [issue #20126][iss20126]), so
1593 it has been disabled for now.
1595 [iss20126]: https://github.com/rust-lang/rust/issues/20126
1599 An associated function for a trait was defined to be static, but an
1600 implementation of the trait declared the same function to be a method (i.e., to
1601 take a `self` parameter).
1603 Here's an example of this error:
1605 ```compile_fail,E0185
1613 // error, method `foo` has a `&self` declaration in the impl, but not in
1621 An associated function for a trait was defined to be a method (i.e., to take a
1622 `self` parameter), but an implementation of the trait declared the same function
1625 Here's an example of this error:
1627 ```compile_fail,E0186
1635 // error, method `foo` has a `&self` declaration in the trait, but not in
1643 Trait objects need to have all associated types specified. Erroneous code
1646 ```compile_fail,E0191
1651 type Foo = Trait; // error: the value of the associated type `Bar` (from
1652 // the trait `Trait`) must be specified
1655 Please verify you specified all associated types of the trait and that you
1656 used the right trait. Example:
1663 type Foo = Trait<Bar=i32>; // ok!
1668 Negative impls are only allowed for auto traits. For more
1669 information see the [opt-in builtin traits RFC][RFC 19].
1671 [RFC 19]: https://github.com/rust-lang/rfcs/blob/master/text/0019-opt-in-builtin-traits.md
1675 #### Note: this error code is no longer emitted by the compiler.
1677 `where` clauses must use generic type parameters: it does not make sense to use
1678 them otherwise. An example causing this error:
1685 #[derive(Copy,Clone)]
1690 impl Foo for Wrapper<u32> where Wrapper<u32>: Clone {
1695 This use of a `where` clause is strange - a more common usage would look
1696 something like the following:
1703 #[derive(Copy,Clone)]
1707 impl <T> Foo for Wrapper<T> where Wrapper<T>: Clone {
1712 Here, we're saying that the implementation exists on Wrapper only when the
1713 wrapped type `T` implements `Clone`. The `where` clause is important because
1714 some types will not implement `Clone`, and thus will not get this method.
1716 In our erroneous example, however, we're referencing a single concrete type.
1717 Since we know for certain that `Wrapper<u32>` implements `Clone`, there's no
1718 reason to also specify it in a `where` clause.
1722 A type parameter was declared which shadows an existing one. An example of this
1725 ```compile_fail,E0194
1727 fn do_something(&self) -> T;
1728 fn do_something_else<T: Clone>(&self, bar: T);
1732 In this example, the trait `Foo` and the trait method `do_something_else` both
1733 define a type parameter `T`. This is not allowed: if the method wishes to
1734 define a type parameter, it must use a different name for it.
1738 Your method's lifetime parameters do not match the trait declaration.
1739 Erroneous code example:
1741 ```compile_fail,E0195
1743 fn bar<'a,'b:'a>(x: &'a str, y: &'b str);
1748 impl Trait for Foo {
1749 fn bar<'a,'b>(x: &'a str, y: &'b str) {
1750 // error: lifetime parameters or bounds on method `bar`
1751 // do not match the trait declaration
1756 The lifetime constraint `'b` for bar() implementation does not match the
1757 trait declaration. Ensure lifetime declarations match exactly in both trait
1758 declaration and implementation. Example:
1762 fn t<'a,'b:'a>(x: &'a str, y: &'b str);
1767 impl Trait for Foo {
1768 fn t<'a,'b:'a>(x: &'a str, y: &'b str) { // ok!
1775 Safe traits should not have unsafe implementations, therefore marking an
1776 implementation for a safe trait unsafe will cause a compiler error. Removing
1777 the unsafe marker on the trait noted in the error will resolve this problem.
1779 ```compile_fail,E0199
1784 // this won't compile because Bar is safe
1785 unsafe impl Bar for Foo { }
1786 // this will compile
1787 impl Bar for Foo { }
1792 Unsafe traits must have unsafe implementations. This error occurs when an
1793 implementation for an unsafe trait isn't marked as unsafe. This may be resolved
1794 by marking the unsafe implementation as unsafe.
1796 ```compile_fail,E0200
1799 unsafe trait Bar { }
1801 // this won't compile because Bar is unsafe and impl isn't unsafe
1802 impl Bar for Foo { }
1803 // this will compile
1804 unsafe impl Bar for Foo { }
1809 It is an error to define two associated items (like methods, associated types,
1810 associated functions, etc.) with the same identifier.
1814 ```compile_fail,E0201
1818 fn bar(&self) -> bool { self.0 > 5 }
1819 fn bar() {} // error: duplicate associated function
1824 fn baz(&self) -> bool;
1830 fn baz(&self) -> bool { true }
1832 // error: duplicate method
1833 fn baz(&self) -> bool { self.0 > 5 }
1835 // error: duplicate associated type
1840 Note, however, that items with the same name are allowed for inherent `impl`
1841 blocks that don't overlap:
1847 fn bar(&self) -> bool { self.0 > 5 }
1851 fn bar(&self) -> bool { self.0 }
1857 Inherent associated types were part of [RFC 195] but are not yet implemented.
1858 See [the tracking issue][iss8995] for the status of this implementation.
1860 [RFC 195]: https://github.com/rust-lang/rfcs/blob/master/text/0195-associated-items.md
1861 [iss8995]: https://github.com/rust-lang/rust/issues/8995
1865 An attempt to implement the `Copy` trait for a struct failed because one of the
1866 fields does not implement `Copy`. To fix this, you must implement `Copy` for the
1867 mentioned field. Note that this may not be possible, as in the example of
1869 ```compile_fail,E0204
1874 impl Copy for Foo { }
1877 This fails because `Vec<T>` does not implement `Copy` for any `T`.
1879 Here's another example that will fail:
1881 ```compile_fail,E0204
1888 This fails because `&mut T` is not `Copy`, even when `T` is `Copy` (this
1889 differs from the behavior for `&T`, which is always `Copy`).
1894 An attempt to implement the `Copy` trait for an enum failed because one of the
1895 variants does not implement `Copy`. To fix this, you must implement `Copy` for
1896 the mentioned variant. Note that this may not be possible, as in the example of
1898 ```compile_fail,E0205
1904 impl Copy for Foo { }
1907 This fails because `Vec<T>` does not implement `Copy` for any `T`.
1909 Here's another example that will fail:
1911 ```compile_fail,E0205
1919 This fails because `&mut T` is not `Copy`, even when `T` is `Copy` (this
1920 differs from the behavior for `&T`, which is always `Copy`).
1925 You can only implement `Copy` for a struct or enum. Both of the following
1926 examples will fail, because neither `[u8; 256]` nor `&'static mut Bar`
1927 (mutable reference to `Bar`) is a struct or enum:
1929 ```compile_fail,E0206
1930 type Foo = [u8; 256];
1931 impl Copy for Foo { } // error
1933 #[derive(Copy, Clone)]
1935 impl Copy for &'static mut Bar { } // error
1940 Any type parameter or lifetime parameter of an `impl` must meet at least one of
1941 the following criteria:
1943 - it appears in the _implementing type_ of the impl, e.g. `impl<T> Foo<T>`
1944 - for a trait impl, it appears in the _implemented trait_, e.g.
1945 `impl<T> SomeTrait<T> for Foo`
1946 - it is bound as an associated type, e.g. `impl<T, U> SomeTrait for T
1947 where T: AnotherTrait<AssocType=U>`
1951 Suppose we have a struct `Foo` and we would like to define some methods for it.
1952 The following definition leads to a compiler error:
1954 ```compile_fail,E0207
1957 impl<T: Default> Foo {
1958 // error: the type parameter `T` is not constrained by the impl trait, self
1959 // type, or predicates [E0207]
1960 fn get(&self) -> T {
1961 <T as Default>::default()
1966 The problem is that the parameter `T` does not appear in the implementing type
1967 (`Foo`) of the impl. In this case, we can fix the error by moving the type
1968 parameter from the `impl` to the method `get`:
1974 // Move the type parameter from the impl to the method
1976 fn get<T: Default>(&self) -> T {
1977 <T as Default>::default()
1984 As another example, suppose we have a `Maker` trait and want to establish a
1985 type `FooMaker` that makes `Foo`s:
1987 ```compile_fail,E0207
1990 fn make(&mut self) -> Self::Item;
1999 impl<T: Default> Maker for FooMaker {
2000 // error: the type parameter `T` is not constrained by the impl trait, self
2001 // type, or predicates [E0207]
2004 fn make(&mut self) -> Foo<T> {
2005 Foo { foo: <T as Default>::default() }
2010 This fails to compile because `T` does not appear in the trait or in the
2013 One way to work around this is to introduce a phantom type parameter into
2014 `FooMaker`, like so:
2017 use std::marker::PhantomData;
2021 fn make(&mut self) -> Self::Item;
2028 // Add a type parameter to `FooMaker`
2029 struct FooMaker<T> {
2030 phantom: PhantomData<T>,
2033 impl<T: Default> Maker for FooMaker<T> {
2036 fn make(&mut self) -> Foo<T> {
2038 foo: <T as Default>::default(),
2044 Another way is to do away with the associated type in `Maker` and use an input
2045 type parameter instead:
2048 // Use a type parameter instead of an associated type here
2050 fn make(&mut self) -> Item;
2059 impl<T: Default> Maker<Foo<T>> for FooMaker {
2060 fn make(&mut self) -> Foo<T> {
2061 Foo { foo: <T as Default>::default() }
2066 ### Additional information
2068 For more information, please see [RFC 447].
2070 [RFC 447]: https://github.com/rust-lang/rfcs/blob/master/text/0447-no-unused-impl-parameters.md
2074 This error indicates a violation of one of Rust's orphan rules for trait
2075 implementations. The rule concerns the use of type parameters in an
2076 implementation of a foreign trait (a trait defined in another crate), and
2077 states that type parameters must be "covered" by a local type. To understand
2078 what this means, it is perhaps easiest to consider a few examples.
2080 If `ForeignTrait` is a trait defined in some external crate `foo`, then the
2081 following trait `impl` is an error:
2083 ```compile_fail,E0210
2084 # #[cfg(for_demonstration_only)]
2086 # #[cfg(for_demonstration_only)]
2087 use foo::ForeignTrait;
2088 # use std::panic::UnwindSafe as ForeignTrait;
2090 impl<T> ForeignTrait for T { } // error
2094 To work around this, it can be covered with a local type, `MyType`:
2097 # use std::panic::UnwindSafe as ForeignTrait;
2098 struct MyType<T>(T);
2099 impl<T> ForeignTrait for MyType<T> { } // Ok
2102 Please note that a type alias is not sufficient.
2104 For another example of an error, suppose there's another trait defined in `foo`
2105 named `ForeignTrait2` that takes two type parameters. Then this `impl` results
2106 in the same rule violation:
2108 ```ignore (cannot-doctest-multicrate-project)
2110 impl<T> ForeignTrait2<T, MyType<T>> for MyType2 { } // error
2113 The reason for this is that there are two appearances of type parameter `T` in
2114 the `impl` header, both as parameters for `ForeignTrait2`. The first appearance
2115 is uncovered, and so runs afoul of the orphan rule.
2117 Consider one more example:
2119 ```ignore (cannot-doctest-multicrate-project)
2120 impl<T> ForeignTrait2<MyType<T>, T> for MyType2 { } // Ok
2123 This only differs from the previous `impl` in that the parameters `T` and
2124 `MyType<T>` for `ForeignTrait2` have been swapped. This example does *not*
2125 violate the orphan rule; it is permitted.
2127 To see why that last example was allowed, you need to understand the general
2128 rule. Unfortunately this rule is a bit tricky to state. Consider an `impl`:
2130 ```ignore (only-for-syntax-highlight)
2131 impl<P1, ..., Pm> ForeignTrait<T1, ..., Tn> for T0 { ... }
2134 where `P1, ..., Pm` are the type parameters of the `impl` and `T0, ..., Tn`
2135 are types. One of the types `T0, ..., Tn` must be a local type (this is another
2136 orphan rule, see the explanation for E0117). Let `i` be the smallest integer
2137 such that `Ti` is a local type. Then no type parameter can appear in any of the
2140 For information on the design of the orphan rules, see [RFC 1023].
2142 [RFC 1023]: https://github.com/rust-lang/rfcs/blob/master/text/1023-rebalancing-coherence.md
2147 You used a function or type which doesn't fit the requirements for where it was
2148 used. Erroneous code examples:
2151 #![feature(intrinsics)]
2153 extern "rust-intrinsic" {
2154 fn size_of<T>(); // error: intrinsic has wrong type
2159 fn main() -> i32 { 0 }
2160 // error: main function expects type: `fn() {main}`: expected (), found i32
2167 // error: mismatched types in range: expected u8, found i8
2177 fn x(self: Rc<Foo>) {}
2178 // error: mismatched self type: expected `Foo`: expected struct
2179 // `Foo`, found struct `alloc::rc::Rc`
2183 For the first code example, please check the function definition. Example:
2186 #![feature(intrinsics)]
2188 extern "rust-intrinsic" {
2189 fn size_of<T>() -> usize; // ok!
2193 The second case example is a bit particular : the main function must always
2194 have this definition:
2200 They never take parameters and never return types.
2202 For the third example, when you match, all patterns must have the same type
2203 as the type you're matching on. Example:
2209 0u8..=3u8 => (), // ok!
2214 And finally, for the last example, only `Box<Self>`, `&Self`, `Self`,
2215 or `&mut Self` work as explicit self parameters. Example:
2221 fn x(self: Box<Foo>) {} // ok!
2228 You used an associated type which isn't defined in the trait.
2229 Erroneous code example:
2231 ```compile_fail,E0220
2236 type Foo = T1<F=i32>; // error: associated type `F` not found for `T1`
2243 // error: Baz is used but not declared
2244 fn return_bool(&self, _: &Self::Bar, _: &Self::Baz) -> bool;
2248 Make sure that you have defined the associated type in the trait body.
2249 Also, verify that you used the right trait or you didn't misspell the
2250 associated type name. Example:
2257 type Foo = T1<Bar=i32>; // ok!
2263 type Baz; // we declare `Baz` in our trait.
2265 // and now we can use it here:
2266 fn return_bool(&self, _: &Self::Bar, _: &Self::Baz) -> bool;
2272 An attempt was made to retrieve an associated type, but the type was ambiguous.
2275 ```compile_fail,E0221
2291 In this example, `Foo` defines an associated type `A`. `Bar` inherits that type
2292 from `Foo`, and defines another associated type of the same name. As a result,
2293 when we attempt to use `Self::A`, it's ambiguous whether we mean the `A` defined
2294 by `Foo` or the one defined by `Bar`.
2296 There are two options to work around this issue. The first is simply to rename
2297 one of the types. Alternatively, one can specify the intended type using the
2311 let _: <Self as Bar>::A;
2318 An attempt was made to retrieve an associated type, but the type was ambiguous.
2321 ```compile_fail,E0223
2322 trait MyTrait {type X; }
2325 let foo: MyTrait::X;
2329 The problem here is that we're attempting to take the type of X from MyTrait.
2330 Unfortunately, the type of X is not defined, because it's only made concrete in
2331 implementations of the trait. A working version of this code might look like:
2334 trait MyTrait {type X; }
2337 impl MyTrait for MyStruct {
2342 let foo: <MyStruct as MyTrait>::X;
2346 This syntax specifies that we want the X type from MyTrait, as made concrete in
2347 MyStruct. The reason that we cannot simply use `MyStruct::X` is that MyStruct
2348 might implement two different traits with identically-named associated types.
2349 This syntax allows disambiguation between the two.
2353 You attempted to use multiple types as bounds for a closure or trait object.
2354 Rust does not currently support this. A simple example that causes this error:
2356 ```compile_fail,E0225
2358 let _: Box<dyn std::io::Read + std::io::Write>;
2362 Auto traits such as Send and Sync are an exception to this rule:
2363 It's possible to have bounds of one non-builtin trait, plus any number of
2364 auto traits. For example, the following compiles correctly:
2368 let _: Box<dyn std::io::Read + Send + Sync>;
2374 An associated type binding was done outside of the type parameter declaration
2375 and `where` clause. Erroneous code example:
2377 ```compile_fail,E0229
2380 fn boo(&self) -> <Self as Foo>::A;
2385 impl Foo for isize {
2387 fn boo(&self) -> usize { 42 }
2390 fn baz<I>(x: &<I as Foo<A=Bar>>::A) {}
2391 // error: associated type bindings are not allowed here
2394 To solve this error, please move the type bindings in the type parameter
2399 # trait Foo { type A; }
2400 fn baz<I: Foo<A=Bar>>(x: &<I as Foo>::A) {} // ok!
2403 Or in the `where` clause:
2407 # trait Foo { type A; }
2408 fn baz<I>(x: &<I as Foo>::A) where I: Foo<A=Bar> {}
2413 #### Note: this error code is no longer emitted by the compiler.
2415 This error indicates that not enough type parameters were found in a type or
2418 For example, the `Foo` struct below is defined to be generic in `T`, but the
2419 type parameter is missing in the definition of `Bar`:
2421 ```compile_fail,E0107
2422 struct Foo<T> { x: T }
2424 struct Bar { x: Foo }
2429 #### Note: this error code is no longer emitted by the compiler.
2431 This error indicates that too many type parameters were found in a type or
2434 For example, the `Foo` struct below has no type parameters, but is supplied
2435 with two in the definition of `Bar`:
2437 ```compile_fail,E0107
2438 struct Foo { x: bool }
2440 struct Bar<S, T> { x: Foo<S, T> }
2445 A cross-crate opt-out trait was implemented on something which wasn't a struct
2446 or enum type. Erroneous code example:
2448 ```compile_fail,E0321
2449 #![feature(optin_builtin_traits)]
2453 impl !Sync for Foo {}
2455 unsafe impl Send for &'static Foo {}
2456 // error: cross-crate traits with a default impl, like `core::marker::Send`,
2457 // can only be implemented for a struct/enum type, not
2461 Only structs and enums are permitted to impl Send, Sync, and other opt-out
2462 trait, and the struct or enum must be local to the current crate. So, for
2463 example, `unsafe impl Send for Rc<Foo>` is not allowed.
2467 The `Sized` trait is a special trait built-in to the compiler for types with a
2468 constant size known at compile-time. This trait is automatically implemented
2469 for types as needed by the compiler, and it is currently disallowed to
2470 explicitly implement it for a type.
2474 An associated const was implemented when another trait item was expected.
2475 Erroneous code example:
2477 ```compile_fail,E0323
2486 // error: item `N` is an associated const, which doesn't match its
2487 // trait `<Bar as Foo>`
2491 Please verify that the associated const wasn't misspelled and the correct trait
2492 was implemented. Example:
2502 type N = u32; // ok!
2516 const N : u32 = 0; // ok!
2522 A method was implemented when another trait item was expected. Erroneous
2525 ```compile_fail,E0324
2536 // error: item `N` is an associated method, which doesn't match its
2537 // trait `<Bar as Foo>`
2541 To fix this error, please verify that the method name wasn't misspelled and
2542 verify that you are indeed implementing the correct trait items. Example:
2562 An associated type was implemented when another trait item was expected.
2563 Erroneous code example:
2565 ```compile_fail,E0325
2574 // error: item `N` is an associated type, which doesn't match its
2575 // trait `<Bar as Foo>`
2579 Please verify that the associated type name wasn't misspelled and your
2580 implementation corresponds to the trait definition. Example:
2590 type N = u32; // ok!
2604 const N : u32 = 0; // ok!
2610 The types of any associated constants in a trait implementation must match the
2611 types in the trait definition. This error indicates that there was a mismatch.
2613 Here's an example of this error:
2615 ```compile_fail,E0326
2623 const BAR: u32 = 5; // error, expected bool, found u32
2629 The Unsize trait should not be implemented directly. All implementations of
2630 Unsize are provided automatically by the compiler.
2632 Erroneous code example:
2634 ```compile_fail,E0328
2637 use std::marker::Unsize;
2641 impl<T> Unsize<T> for MyType {}
2644 If you are defining your own smart pointer type and would like to enable
2645 conversion from a sized to an unsized type with the
2646 [DST coercion system][RFC 982], use [`CoerceUnsized`] instead.
2649 #![feature(coerce_unsized)]
2651 use std::ops::CoerceUnsized;
2653 pub struct MyType<T: ?Sized> {
2654 field_with_unsized_type: T,
2657 impl<T, U> CoerceUnsized<MyType<U>> for MyType<T>
2658 where T: CoerceUnsized<U> {}
2661 [RFC 982]: https://github.com/rust-lang/rfcs/blob/master/text/0982-dst-coercion.md
2662 [`CoerceUnsized`]: https://doc.rust-lang.org/std/ops/trait.CoerceUnsized.html
2666 // Associated consts can now be accessed through generic type parameters, and
2667 // this error is no longer emitted.
2669 // FIXME: consider whether to leave it in the error index, or remove it entirely
2670 // as associated consts is not stabilized yet.
2673 An attempt was made to access an associated constant through either a generic
2674 type parameter or `Self`. This is not supported yet. An example causing this
2675 error is shown below:
2684 impl Foo for MyStruct {
2685 const BAR: f64 = 0f64;
2688 fn get_bar_bad<F: Foo>(t: F) -> f64 {
2693 Currently, the value of `BAR` for a particular type can only be accessed
2694 through a concrete type, as shown below:
2703 fn get_bar_good() -> f64 {
2704 <MyStruct as Foo>::BAR
2711 An attempt was made to implement `Drop` on a concrete specialization of a
2712 generic type. An example is shown below:
2714 ```compile_fail,E0366
2719 impl Drop for Foo<u32> {
2720 fn drop(&mut self) {}
2724 This code is not legal: it is not possible to specialize `Drop` to a subset of
2725 implementations of a generic type. One workaround for this is to wrap the
2726 generic type, as shown below:
2738 fn drop(&mut self) {}
2744 An attempt was made to implement `Drop` on a specialization of a generic type.
2745 An example is shown below:
2747 ```compile_fail,E0367
2750 struct MyStruct<T> {
2754 impl<T: Foo> Drop for MyStruct<T> {
2755 fn drop(&mut self) {}
2759 This code is not legal: it is not possible to specialize `Drop` to a subset of
2760 implementations of a generic type. In order for this code to work, `MyStruct`
2761 must also require that `T` implements `Foo`. Alternatively, another option is
2762 to wrap the generic type in another that specializes appropriately:
2767 struct MyStruct<T> {
2771 struct MyStructWrapper<T: Foo> {
2775 impl <T: Foo> Drop for MyStructWrapper<T> {
2776 fn drop(&mut self) {}
2782 This error indicates that a binary assignment operator like `+=` or `^=` was
2783 applied to a type that doesn't support it. For example:
2785 ```compile_fail,E0368
2786 let mut x = 12f32; // error: binary operation `<<` cannot be applied to
2792 To fix this error, please check that this type implements this binary
2796 let mut x = 12u32; // the `u32` type does implement the `ShlAssign` trait
2801 It is also possible to overload most operators for your own type by
2802 implementing the `[OP]Assign` traits from `std::ops`.
2804 Another problem you might be facing is this: suppose you've overloaded the `+`
2805 operator for some type `Foo` by implementing the `std::ops::Add` trait for
2806 `Foo`, but you find that using `+=` does not work, as in this example:
2808 ```compile_fail,E0368
2816 fn add(self, rhs: Foo) -> Foo {
2822 let mut x: Foo = Foo(5);
2823 x += Foo(7); // error, `+= cannot be applied to the type `Foo`
2827 This is because `AddAssign` is not automatically implemented, so you need to
2828 manually implement it for your type.
2832 A binary operation was attempted on a type which doesn't support it.
2833 Erroneous code example:
2835 ```compile_fail,E0369
2836 let x = 12f32; // error: binary operation `<<` cannot be applied to
2842 To fix this error, please check that this type implements this binary
2846 let x = 12u32; // the `u32` type does implement it:
2847 // https://doc.rust-lang.org/stable/std/ops/trait.Shl.html
2852 It is also possible to overload most operators for your own type by
2853 implementing traits from `std::ops`.
2855 String concatenation appends the string on the right to the string on the
2856 left and may require reallocation. This requires ownership of the string
2857 on the left. If something should be added to a string literal, move the
2858 literal to the heap by allocating it with `to_owned()` like in
2859 `"Your text".to_owned()`.
2864 The maximum value of an enum was reached, so it cannot be automatically
2865 set in the next enum value. Erroneous code example:
2867 ```compile_fail,E0370
2870 X = 0x7fffffffffffffff,
2871 Y, // error: enum discriminant overflowed on value after
2872 // 9223372036854775807: i64; set explicitly via
2873 // Y = -9223372036854775808 if that is desired outcome
2877 To fix this, please set manually the next enum value or put the enum variant
2878 with the maximum value at the end of the enum. Examples:
2883 X = 0x7fffffffffffffff,
2894 X = 0x7fffffffffffffff,
2900 When `Trait2` is a subtrait of `Trait1` (for example, when `Trait2` has a
2901 definition like `trait Trait2: Trait1 { ... }`), it is not allowed to implement
2902 `Trait1` for `Trait2`. This is because `Trait2` already implements `Trait1` by
2903 definition, so it is not useful to do this.
2907 ```compile_fail,E0371
2908 trait Foo { fn foo(&self) { } }
2912 impl Bar for Baz { } // error, `Baz` implements `Bar` by definition
2913 impl Foo for Baz { } // error, `Baz` implements `Bar` which implements `Foo`
2914 impl Baz for Baz { } // error, `Baz` (trivially) implements `Baz`
2915 impl Baz for Bar { } // Note: This is OK
2920 A struct without a field containing an unsized type cannot implement
2921 `CoerceUnsized`. An [unsized type][1] is any type that the compiler
2922 doesn't know the length or alignment of at compile time. Any struct
2923 containing an unsized type is also unsized.
2925 [1]: https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait
2927 Example of erroneous code:
2929 ```compile_fail,E0374
2930 #![feature(coerce_unsized)]
2931 use std::ops::CoerceUnsized;
2933 struct Foo<T: ?Sized> {
2937 // error: Struct `Foo` has no unsized fields that need `CoerceUnsized`.
2938 impl<T, U> CoerceUnsized<Foo<U>> for Foo<T>
2939 where T: CoerceUnsized<U> {}
2942 `CoerceUnsized` is used to coerce one struct containing an unsized type
2943 into another struct containing a different unsized type. If the struct
2944 doesn't have any fields of unsized types then you don't need explicit
2945 coercion to get the types you want. To fix this you can either
2946 not try to implement `CoerceUnsized` or you can add a field that is
2947 unsized to the struct.
2952 #![feature(coerce_unsized)]
2953 use std::ops::CoerceUnsized;
2955 // We don't need to impl `CoerceUnsized` here.
2960 // We add the unsized type field to the struct.
2961 struct Bar<T: ?Sized> {
2966 // The struct has an unsized field so we can implement
2967 // `CoerceUnsized` for it.
2968 impl<T, U> CoerceUnsized<Bar<U>> for Bar<T>
2969 where T: CoerceUnsized<U> {}
2972 Note that `CoerceUnsized` is mainly used by smart pointers like `Box`, `Rc`
2973 and `Arc` to be able to mark that they can coerce unsized types that they
2978 A struct with more than one field containing an unsized type cannot implement
2979 `CoerceUnsized`. This only occurs when you are trying to coerce one of the
2980 types in your struct to another type in the struct. In this case we try to
2981 impl `CoerceUnsized` from `T` to `U` which are both types that the struct
2982 takes. An [unsized type][1] is any type that the compiler doesn't know the
2983 length or alignment of at compile time. Any struct containing an unsized type
2986 Example of erroneous code:
2988 ```compile_fail,E0375
2989 #![feature(coerce_unsized)]
2990 use std::ops::CoerceUnsized;
2992 struct Foo<T: ?Sized, U: ?Sized> {
2998 // error: Struct `Foo` has more than one unsized field.
2999 impl<T, U> CoerceUnsized<Foo<U, T>> for Foo<T, U> {}
3002 `CoerceUnsized` only allows for coercion from a structure with a single
3003 unsized type field to another struct with a single unsized type field.
3004 In fact Rust only allows for a struct to have one unsized type in a struct
3005 and that unsized type must be the last field in the struct. So having two
3006 unsized types in a single struct is not allowed by the compiler. To fix this
3007 use only one field containing an unsized type in the struct and then use
3008 multiple structs to manage each unsized type field you need.
3013 #![feature(coerce_unsized)]
3014 use std::ops::CoerceUnsized;
3016 struct Foo<T: ?Sized> {
3021 impl <T, U> CoerceUnsized<Foo<U>> for Foo<T>
3022 where T: CoerceUnsized<U> {}
3024 fn coerce_foo<T: CoerceUnsized<U>, U>(t: T) -> Foo<U> {
3025 Foo { a: 12i32, b: t } // we use coercion to get the `Foo<U>` type we need
3029 [1]: https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait
3033 The type you are trying to impl `CoerceUnsized` for is not a struct.
3034 `CoerceUnsized` can only be implemented for a struct. Unsized types are
3035 already able to be coerced without an implementation of `CoerceUnsized`
3036 whereas a struct containing an unsized type needs to know the unsized type
3037 field it's containing is able to be coerced. An [unsized type][1]
3038 is any type that the compiler doesn't know the length or alignment of at
3039 compile time. Any struct containing an unsized type is also unsized.
3041 [1]: https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait
3043 Example of erroneous code:
3045 ```compile_fail,E0376
3046 #![feature(coerce_unsized)]
3047 use std::ops::CoerceUnsized;
3049 struct Foo<T: ?Sized> {
3053 // error: The type `U` is not a struct
3054 impl<T, U> CoerceUnsized<U> for Foo<T> {}
3057 The `CoerceUnsized` trait takes a struct type. Make sure the type you are
3058 providing to `CoerceUnsized` is a struct with only the last field containing an
3064 #![feature(coerce_unsized)]
3065 use std::ops::CoerceUnsized;
3071 // The `Foo<U>` is a struct so `CoerceUnsized` can be implemented
3072 impl<T, U> CoerceUnsized<Foo<U>> for Foo<T> where T: CoerceUnsized<U> {}
3075 Note that in Rust, structs can only contain an unsized type if the field
3076 containing the unsized type is the last and only unsized type field in the
3081 The `DispatchFromDyn` trait currently can only be implemented for
3082 builtin pointer types and structs that are newtype wrappers around them
3083 — that is, the struct must have only one field (except for`PhantomData`),
3084 and that field must itself implement `DispatchFromDyn`.
3089 #![feature(dispatch_from_dyn, unsize)]
3092 ops::DispatchFromDyn,
3095 struct Ptr<T: ?Sized>(*const T);
3097 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Ptr<U>> for Ptr<T>
3104 #![feature(dispatch_from_dyn)]
3106 ops::DispatchFromDyn,
3107 marker::PhantomData,
3112 _phantom: PhantomData<()>,
3115 impl<T, U> DispatchFromDyn<Wrapper<U>> for Wrapper<T>
3117 T: DispatchFromDyn<U>,
3121 Example of illegal `DispatchFromDyn` implementation
3122 (illegal because of extra field)
3124 ```compile-fail,E0378
3125 #![feature(dispatch_from_dyn)]
3126 use std::ops::DispatchFromDyn;
3128 struct WrapperExtraField<T> {
3133 impl<T, U> DispatchFromDyn<WrapperExtraField<U>> for WrapperExtraField<T>
3135 T: DispatchFromDyn<U>,
3141 You tried to implement methods for a primitive type. Erroneous code example:
3143 ```compile_fail,E0390
3149 // error: only a single inherent implementation marked with
3150 // `#[lang = "mut_ptr"]` is allowed for the `*mut T` primitive
3153 This isn't allowed, but using a trait to implement a method is a good solution.
3165 impl Bar for *mut Foo {
3172 This error indicates that a type or lifetime parameter has been declared
3173 but not actually used. Here is an example that demonstrates the error:
3175 ```compile_fail,E0392
3181 If the type parameter was included by mistake, this error can be fixed
3182 by simply removing the type parameter, as shown below:
3190 Alternatively, if the type parameter was intentionally inserted, it must be
3191 used. A simple fix is shown below:
3199 This error may also commonly be found when working with unsafe code. For
3200 example, when using raw pointers one may wish to specify the lifetime for
3201 which the pointed-at data is valid. An initial attempt (below) causes this
3204 ```compile_fail,E0392
3210 We want to express the constraint that Foo should not outlive `'a`, because
3211 the data pointed to by `T` is only valid for that lifetime. The problem is
3212 that there are no actual uses of `'a`. It's possible to work around this
3213 by adding a PhantomData type to the struct, using it to tell the compiler
3214 to act as if the struct contained a borrowed reference `&'a T`:
3217 use std::marker::PhantomData;
3219 struct Foo<'a, T: 'a> {
3221 phantom: PhantomData<&'a T>
3225 [PhantomData] can also be used to express information about unused type
3228 [PhantomData]: https://doc.rust-lang.org/std/marker/struct.PhantomData.html
3232 A type parameter which references `Self` in its default value was not specified.
3233 Example of erroneous code:
3235 ```compile_fail,E0393
3238 fn together_we_will_rule_the_galaxy(son: &A) {}
3239 // error: the type parameter `T` must be explicitly specified in an
3240 // object type because its default value `Self` references the
3244 A trait object is defined over a single, fully-defined trait. With a regular
3245 default parameter, this parameter can just be substituted in. However, if the
3246 default parameter is `Self`, the trait changes for each concrete type; i.e.
3247 `i32` will be expected to implement `A<i32>`, `bool` will be expected to
3248 implement `A<bool>`, etc... These types will not share an implementation of a
3249 fully-defined trait; instead they share implementations of a trait with
3250 different parameters substituted in for each implementation. This is
3251 irreconcilable with what we need to make a trait object work, and is thus
3252 disallowed. Making the trait concrete by explicitly specifying the value of the
3253 defaulted parameter will fix this issue. Fixed example:
3258 fn together_we_will_rule_the_galaxy(son: &A<i32>) {} // Ok!
3263 You implemented a trait, overriding one or more of its associated types but did
3264 not reimplement its default methods.
3266 Example of erroneous code:
3268 ```compile_fail,E0399
3269 #![feature(associated_type_defaults)]
3277 // error - the following trait items need to be reimplemented as
3278 // `Assoc` was overridden: `bar`
3283 To fix this, add an implementation for each default method from the trait:
3286 #![feature(associated_type_defaults)]
3295 fn bar(&self) {} // ok!
3301 The functional record update syntax is only allowed for structs. (Struct-like
3302 enum variants don't qualify, for example.)
3304 Erroneous code example:
3306 ```compile_fail,E0436
3307 enum PublicationFrequency {
3309 SemiMonthly { days: (u8, u8), annual_special: bool },
3312 fn one_up_competitor(competitor_frequency: PublicationFrequency)
3313 -> PublicationFrequency {
3314 match competitor_frequency {
3315 PublicationFrequency::Weekly => PublicationFrequency::SemiMonthly {
3316 days: (1, 15), annual_special: false
3318 c @ PublicationFrequency::SemiMonthly{ .. } =>
3319 PublicationFrequency::SemiMonthly {
3320 annual_special: true, ..c // error: functional record update
3321 // syntax requires a struct
3327 Rewrite the expression without functional record update syntax:
3330 enum PublicationFrequency {
3332 SemiMonthly { days: (u8, u8), annual_special: bool },
3335 fn one_up_competitor(competitor_frequency: PublicationFrequency)
3336 -> PublicationFrequency {
3337 match competitor_frequency {
3338 PublicationFrequency::Weekly => PublicationFrequency::SemiMonthly {
3339 days: (1, 15), annual_special: false
3341 PublicationFrequency::SemiMonthly{ days, .. } =>
3342 PublicationFrequency::SemiMonthly {
3343 days, annual_special: true // ok!
3351 The length of the platform-intrinsic function `simd_shuffle`
3352 wasn't specified. Erroneous code example:
3354 ```compile_fail,E0439
3355 #![feature(platform_intrinsics)]
3357 extern "platform-intrinsic" {
3358 fn simd_shuffle<A,B>(a: A, b: A, c: [u32; 8]) -> B;
3359 // error: invalid `simd_shuffle`, needs length: `simd_shuffle`
3363 The `simd_shuffle` function needs the length of the array passed as
3364 last parameter in its name. Example:
3367 #![feature(platform_intrinsics)]
3369 extern "platform-intrinsic" {
3370 fn simd_shuffle8<A,B>(a: A, b: A, c: [u32; 8]) -> B;
3376 The `typeof` keyword is currently reserved but unimplemented.
3377 Erroneous code example:
3379 ```compile_fail,E0516
3381 let x: typeof(92) = 92;
3385 Try using type inference instead. Example:
3395 A non-default implementation was already made on this type so it cannot be
3396 specialized further. Erroneous code example:
3398 ```compile_fail,E0520
3399 #![feature(specialization)]
3406 impl<T> SpaceLlama for T {
3407 default fn fly(&self) {}
3411 // applies to all `Clone` T and overrides the previous impl
3412 impl<T: Clone> SpaceLlama for T {
3416 // since `i32` is clone, this conflicts with the previous implementation
3417 impl SpaceLlama for i32 {
3418 default fn fly(&self) {}
3419 // error: item `fly` is provided by an `impl` that specializes
3420 // another, but the item in the parent `impl` is not marked
3421 // `default` and so it cannot be specialized.
3425 Specialization only allows you to override `default` functions in
3428 To fix this error, you need to mark all the parent implementations as default.
3432 #![feature(specialization)]
3439 impl<T> SpaceLlama for T {
3440 default fn fly(&self) {} // This is a parent implementation.
3443 // applies to all `Clone` T; overrides the previous impl
3444 impl<T: Clone> SpaceLlama for T {
3445 default fn fly(&self) {} // This is a parent implementation but was
3446 // previously not a default one, causing the error
3449 // applies to i32, overrides the previous two impls
3450 impl SpaceLlama for i32 {
3451 fn fly(&self) {} // And now that's ok!
3457 The number of elements in an array or slice pattern differed from the number of
3458 elements in the array being matched.
3460 Example of erroneous code:
3462 ```compile_fail,E0527
3463 let r = &[1, 2, 3, 4];
3465 &[a, b] => { // error: pattern requires 2 elements but array
3467 println!("a={}, b={}", a, b);
3472 Ensure that the pattern is consistent with the size of the matched
3473 array. Additional elements can be matched with `..`:
3476 #![feature(slice_patterns)]
3478 let r = &[1, 2, 3, 4];
3480 &[a, b, ..] => { // ok!
3481 println!("a={}, b={}", a, b);
3488 An array or slice pattern required more elements than were present in the
3491 Example of erroneous code:
3493 ```compile_fail,E0528
3494 #![feature(slice_patterns)]
3498 &[a, b, c, rest @ ..] => { // error: pattern requires at least 3
3499 // elements but array has 2
3500 println!("a={}, b={}, c={} rest={:?}", a, b, c, rest);
3505 Ensure that the matched array has at least as many elements as the pattern
3506 requires. You can match an arbitrary number of remaining elements with `..`:
3509 #![feature(slice_patterns)]
3511 let r = &[1, 2, 3, 4, 5];
3513 &[a, b, c, rest @ ..] => { // ok!
3514 // prints `a=1, b=2, c=3 rest=[4, 5]`
3515 println!("a={}, b={}, c={} rest={:?}", a, b, c, rest);
3522 An array or slice pattern was matched against some other type.
3524 Example of erroneous code:
3526 ```compile_fail,E0529
3529 [a, b] => { // error: expected an array or slice, found `f32`
3530 println!("a={}, b={}", a, b);
3535 Ensure that the pattern and the expression being matched on are of consistent
3542 println!("a={}, b={}", a, b);
3549 The `inline` attribute was malformed.
3551 Erroneous code example:
3553 ```ignore (compile_fail not working here; see Issue #43707)
3554 #[inline()] // error: expected one argument
3555 pub fn something() {}
3560 The parenthesized `inline` attribute requires the parameter to be specified:
3574 Alternatively, a paren-less version of the attribute may be used to hint the
3575 compiler about inlining opportunity:
3582 For more information about the inline attribute, read:
3583 https://doc.rust-lang.org/reference.html#inline-attributes
3587 An unknown argument was given to the `inline` attribute.
3589 Erroneous code example:
3591 ```ignore (compile_fail not working here; see Issue #43707)
3592 #[inline(unknown)] // error: invalid argument
3593 pub fn something() {}
3598 The `inline` attribute only supports two arguments:
3603 All other arguments given to the `inline` attribute will return this error.
3607 #[inline(never)] // ok!
3608 pub fn something() {}
3613 For more information about the inline attribute, https:
3614 read://doc.rust-lang.org/reference.html#inline-attributes
3618 An unknown field was specified into an enum's structure variant.
3620 Erroneous code example:
3622 ```compile_fail,E0559
3627 let s = Field::Fool { joke: 0 };
3628 // error: struct variant `Field::Fool` has no field named `joke`
3631 Verify you didn't misspell the field's name or that the field exists. Example:
3638 let s = Field::Fool { joke: 0 }; // ok!
3643 An unknown field was specified into a structure.
3645 Erroneous code example:
3647 ```compile_fail,E0560
3652 let s = Simba { mother: 1, father: 0 };
3653 // error: structure `Simba` has no field named `father`
3656 Verify you didn't misspell the field's name or that the field exists. Example:
3664 let s = Simba { mother: 1, father: 0 }; // ok!
3669 If an impl has a generic parameter with the `#[may_dangle]` attribute, then
3670 that impl must be declared as an `unsafe impl.
3672 Erroneous code example:
3674 ```compile_fail,E0569
3675 #![feature(dropck_eyepatch)]
3678 impl<#[may_dangle] X> Drop for Foo<X> {
3679 fn drop(&mut self) { }
3683 In this example, we are asserting that the destructor for `Foo` will not
3684 access any data of type `X`, and require this assertion to be true for
3685 overall safety in our program. The compiler does not currently attempt to
3686 verify this assertion; therefore we must tag this `impl` as unsafe.
3690 The requested ABI is unsupported by the current target.
3692 The rust compiler maintains for each target a blacklist of ABIs unsupported on
3693 that target. If an ABI is present in such a list this usually means that the
3694 target / ABI combination is currently unsupported by llvm.
3696 If necessary, you can circumvent this check using custom target specifications.
3700 A return statement was found outside of a function body.
3702 Erroneous code example:
3704 ```compile_fail,E0572
3705 const FOO: u32 = return 0; // error: return statement outside of function body
3710 To fix this issue, just remove the return keyword or move the expression into a
3716 fn some_fn() -> u32 {
3727 In a `fn` type, a lifetime appears only in the return type,
3728 and not in the arguments types.
3730 Erroneous code example:
3732 ```compile_fail,E0581
3734 // Here, `'a` appears only in the return type:
3735 let x: for<'a> fn() -> &'a i32;
3739 To fix this issue, either use the lifetime in the arguments, or use
3744 // Here, `'a` appears only in the return type:
3745 let x: for<'a> fn(&'a i32) -> &'a i32;
3746 let y: fn() -> &'static i32;
3750 Note: The examples above used to be (erroneously) accepted by the
3751 compiler, but this was since corrected. See [issue #33685] for more
3754 [issue #33685]: https://github.com/rust-lang/rust/issues/33685
3758 A lifetime appears only in an associated-type binding,
3759 and not in the input types to the trait.
3761 Erroneous code example:
3763 ```compile_fail,E0582
3765 // No type can satisfy this requirement, since `'a` does not
3766 // appear in any of the input types (here, `i32`):
3767 where F: for<'a> Fn(i32) -> Option<&'a i32>
3774 To fix this issue, either use the lifetime in the inputs, or use
3778 fn bar<F, G>(t: F, u: G)
3779 where F: for<'a> Fn(&'a i32) -> Option<&'a i32>,
3780 G: Fn(i32) -> Option<&'static i32>,
3787 Note: The examples above used to be (erroneously) accepted by the
3788 compiler, but this was since corrected. See [issue #33685] for more
3791 [issue #33685]: https://github.com/rust-lang/rust/issues/33685
3795 This error occurs when you defined methods or associated functions with same
3798 Erroneous code example:
3800 ```compile_fail,E0592
3804 fn bar() {} // previous definition here
3808 fn bar() {} // duplicate definition here
3812 A similar error is E0201. The difference is whether there is one declaration
3813 block or not. To avoid this error, you must give each `fn` a unique name.
3823 fn baz() {} // define with different name
3829 This error occurs when a method is used on a type which doesn't implement it:
3831 Erroneous code example:
3833 ```compile_fail,E0599
3837 x.chocolate(); // error: no method named `chocolate` found for type `Mouth`
3838 // in the current scope
3843 An unary operator was used on a type which doesn't implement it.
3845 Example of erroneous code:
3847 ```compile_fail,E0600
3853 !Question::Yes; // error: cannot apply unary operator `!` to type `Question`
3856 In this case, `Question` would need to implement the `std::ops::Not` trait in
3857 order to be able to use `!` on it. Let's implement it:
3867 // We implement the `Not` trait on the enum.
3868 impl Not for Question {
3871 fn not(self) -> bool {
3873 Question::Yes => false, // If the `Answer` is `Yes`, then it
3875 Question::No => true, // And here we do the opposite.
3880 assert_eq!(!Question::Yes, false);
3881 assert_eq!(!Question::No, true);
3886 An attempt to index into a type which doesn't implement the `std::ops::Index`
3887 trait was performed.
3889 Erroneous code example:
3891 ```compile_fail,E0608
3892 0u8[2]; // error: cannot index into a value of type `u8`
3895 To be able to index into a type it needs to implement the `std::ops::Index`
3899 let v: Vec<u8> = vec![0, 1, 2, 3];
3901 // The `Vec` type implements the `Index` trait so you can do:
3902 println!("{}", v[2]);
3907 A cast to `char` was attempted on a type other than `u8`.
3909 Erroneous code example:
3911 ```compile_fail,E0604
3912 0u32 as char; // error: only `u8` can be cast as `char`, not `u32`
3915 As the error message indicates, only `u8` can be cast into `char`. Example:
3918 let c = 86u8 as char; // ok!
3922 For more information about casts, take a look at the Type cast section in
3923 [The Reference Book][1].
3925 [1]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
3929 An invalid cast was attempted.
3931 Erroneous code examples:
3933 ```compile_fail,E0605
3935 x as Vec<u8>; // error: non-primitive cast: `u8` as `std::vec::Vec<u8>`
3939 let v = core::ptr::null::<u8>(); // So here, `v` is a `*const u8`.
3940 v as &u8; // error: non-primitive cast: `*const u8` as `&u8`
3943 Only primitive types can be cast into each other. Examples:
3949 let v = core::ptr::null::<u8>();
3950 v as *const i8; // ok!
3953 For more information about casts, take a look at the Type cast section in
3954 [The Reference Book][1].
3956 [1]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
3960 An incompatible cast was attempted.
3962 Erroneous code example:
3964 ```compile_fail,E0606
3965 let x = &0u8; // Here, `x` is a `&u8`.
3966 let y: u32 = x as u32; // error: casting `&u8` as `u32` is invalid
3969 When casting, keep in mind that only primitive types can be cast into each
3974 let y: u32 = *x as u32; // We dereference it first and then cast it.
3977 For more information about casts, take a look at the Type cast section in
3978 [The Reference Book][1].
3980 [1]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
3984 A cast between a thin and a fat pointer was attempted.
3986 Erroneous code example:
3988 ```compile_fail,E0607
3989 let v = core::ptr::null::<u8>();
3993 First: what are thin and fat pointers?
3995 Thin pointers are "simple" pointers: they are purely a reference to a memory
3998 Fat pointers are pointers referencing Dynamically Sized Types (also called DST).
3999 DST don't have a statically known size, therefore they can only exist behind
4000 some kind of pointers that contain additional information. Slices and trait
4001 objects are DSTs. In the case of slices, the additional information the fat
4002 pointer holds is their size.
4004 To fix this error, don't try to cast directly between thin and fat pointers.
4006 For more information about casts, take a look at the Type cast section in
4007 [The Reference Book][1].
4009 [1]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
4013 Attempted to access a non-existent field in a struct.
4015 Erroneous code example:
4017 ```compile_fail,E0609
4018 struct StructWithFields {
4022 let s = StructWithFields { x: 0 };
4023 println!("{}", s.foo); // error: no field `foo` on type `StructWithFields`
4026 To fix this error, check that you didn't misspell the field's name or that the
4027 field actually exists. Example:
4030 struct StructWithFields {
4034 let s = StructWithFields { x: 0 };
4035 println!("{}", s.x); // ok!
4040 Attempted to access a field on a primitive type.
4042 Erroneous code example:
4044 ```compile_fail,E0610
4046 println!("{}", x.foo); // error: `{integer}` is a primitive type, therefore
4047 // doesn't have fields
4050 Primitive types are the most basic types available in Rust and don't have
4051 fields. To access data via named fields, struct types are used. Example:
4054 // We declare struct called `Foo` containing two fields:
4060 // We create an instance of this struct:
4061 let variable = Foo { x: 0, y: -12 };
4062 // And we can now access its fields:
4063 println!("x: {}, y: {}", variable.x, variable.y);
4066 For more information about primitives and structs, take a look at The Book:
4067 https://doc.rust-lang.org/book/ch03-02-data-types.html
4068 https://doc.rust-lang.org/book/ch05-00-structs.html
4072 Attempted to dereference a variable which cannot be dereferenced.
4074 Erroneous code example:
4076 ```compile_fail,E0614
4078 *y; // error: type `u32` cannot be dereferenced
4081 Only types implementing `std::ops::Deref` can be dereferenced (such as `&T`).
4087 // So here, `x` is a `&u32`, so we can dereference it:
4093 Attempted to access a method like a field.
4095 Erroneous code example:
4097 ```compile_fail,E0615
4106 let f = Foo { x: 0 };
4107 f.method; // error: attempted to take value of method `method` on type `Foo`
4110 If you want to use a method, add `()` after it:
4113 # struct Foo { x: u32 }
4114 # impl Foo { fn method(&self) {} }
4115 # let f = Foo { x: 0 };
4119 However, if you wanted to access a field of a struct check that the field name
4120 is spelled correctly. Example:
4123 # struct Foo { x: u32 }
4124 # impl Foo { fn method(&self) {} }
4125 # let f = Foo { x: 0 };
4126 println!("{}", f.x);
4131 Attempted to access a private field on a struct.
4133 Erroneous code example:
4135 ```compile_fail,E0616
4138 x: u32, // So `x` is private in here.
4142 pub fn new() -> Foo { Foo { x: 0 } }
4146 let f = some_module::Foo::new();
4147 println!("{}", f.x); // error: field `x` of struct `some_module::Foo` is private
4150 If you want to access this field, you have two options:
4152 1) Set the field public:
4157 pub x: u32, // `x` is now public.
4161 pub fn new() -> Foo { Foo { x: 0 } }
4165 let f = some_module::Foo::new();
4166 println!("{}", f.x); // ok!
4169 2) Add a getter function:
4174 x: u32, // So `x` is still private in here.
4178 pub fn new() -> Foo { Foo { x: 0 } }
4180 // We create the getter function here:
4181 pub fn get_x(&self) -> &u32 { &self.x }
4185 let f = some_module::Foo::new();
4186 println!("{}", f.get_x()); // ok!
4191 Attempted to pass an invalid type of variable into a variadic function.
4193 Erroneous code example:
4195 ```compile_fail,E0617
4197 fn printf(c: *const i8, ...);
4201 printf(::std::ptr::null(), 0f32);
4202 // error: can't pass an `f32` to variadic function, cast to `c_double`
4206 Certain Rust types must be cast before passing them to a variadic function,
4207 because of arcane ABI rules dictated by the C standard. To fix the error,
4208 cast the value to the type specified by the error message (which you may need
4209 to import from `std::os::raw`).
4213 Attempted to call something which isn't a function nor a method.
4215 Erroneous code examples:
4217 ```compile_fail,E0618
4222 X::Entry(); // error: expected function, found `X::Entry`
4226 x(); // error: expected function, found `i32`
4229 Only functions and methods can be called using `()`. Example:
4232 // We declare a function:
4233 fn i_am_a_function() {}
4241 #### Note: this error code is no longer emitted by the compiler.
4242 The type-checker needed to know the type of an expression, but that type had not
4245 Erroneous code example:
4251 // Here, the type of `v` is not (yet) known, so we
4252 // cannot resolve this method call:
4253 v.to_uppercase(); // error: the type of this value must be known in
4260 Type inference typically proceeds from the top of the function to the bottom,
4261 figuring out types as it goes. In some cases -- notably method calls and
4262 overloadable operators like `*` -- the type checker may not have enough
4263 information *yet* to make progress. This can be true even if the rest of the
4264 function provides enough context (because the type-checker hasn't looked that
4265 far ahead yet). In this case, type annotations can be used to help it along.
4267 To fix this error, just specify the type of the variable. Example:
4270 let mut x: Vec<String> = vec![]; // We precise the type of the vec elements.
4273 v.to_uppercase(); // Since rustc now knows the type of the vec elements,
4274 // we can use `v`'s methods.
4282 A cast to an unsized type was attempted.
4284 Erroneous code example:
4286 ```compile_fail,E0620
4287 let x = &[1_usize, 2] as [usize]; // error: cast to unsized type: `&[usize; 2]`
4291 In Rust, some types don't have a known size at compile-time. For example, in a
4292 slice type like `[u32]`, the number of elements is not known at compile-time and
4293 hence the overall size cannot be computed. As a result, such types can only be
4294 manipulated through a reference (e.g., `&T` or `&mut T`) or other pointer-type
4295 (e.g., `Box` or `Rc`). Try casting to a reference instead:
4298 let x = &[1_usize, 2] as &[usize]; // ok!
4303 An intrinsic was declared without being a function.
4305 Erroneous code example:
4307 ```compile_fail,E0622
4308 #![feature(intrinsics)]
4309 extern "rust-intrinsic" {
4310 pub static breakpoint : unsafe extern "rust-intrinsic" fn();
4311 // error: intrinsic must be a function
4314 fn main() { unsafe { breakpoint(); } }
4317 An intrinsic is a function available for use in a given programming language
4318 whose implementation is handled specially by the compiler. In order to fix this
4319 error, just declare a function.
4323 A private item was used outside of its scope.
4325 Erroneous code example:
4327 ```compile_fail,E0624
4336 let foo = inner::Foo;
4337 foo.method(); // error: method `method` is private
4340 Two possibilities are available to solve this issue:
4342 1. Only use the item in the scope it has been defined:
4352 pub fn call_method(foo: &Foo) { // We create a public function.
4353 foo.method(); // Which calls the item.
4357 let foo = inner::Foo;
4358 inner::call_method(&foo); // And since the function is public, we can call the
4359 // method through it.
4362 2. Make the item public:
4369 pub fn method(&self) {} // It's now public.
4373 let foo = inner::Foo;
4374 foo.method(); // Ok!
4379 This error indicates that the struct, enum or enum variant must be matched
4380 non-exhaustively as it has been marked as `non_exhaustive`.
4382 When applied within a crate, downstream users of the crate will need to use the
4383 `_` pattern when matching enums and use the `..` pattern when matching structs.
4384 Downstream crates cannot match against non-exhaustive enum variants.
4386 For example, in the below example, since the enum is marked as
4387 `non_exhaustive`, it is required that downstream crates match non-exhaustively
4390 ```rust,ignore (pseudo-Rust)
4391 use std::error::Error as StdError;
4393 #[non_exhaustive] pub enum Error {
4398 impl StdError for Error {
4399 fn description(&self) -> &str {
4400 // This will not error, despite being marked as non_exhaustive, as this
4401 // enum is defined within the current crate, it can be matched
4404 Message(ref s) => s,
4405 Other => "other or unknown error",
4411 An example of matching non-exhaustively on the above enum is provided below:
4413 ```rust,ignore (pseudo-Rust)
4416 // This will not error as the non_exhaustive Error enum has been matched with a
4419 Message(ref s) => ...,
4425 Similarly, for structs, match with `..` to avoid this error.
4429 This error indicates that the struct, enum or enum variant cannot be
4430 instantiated from outside of the defining crate as it has been marked
4431 as `non_exhaustive` and as such more fields/variants may be added in
4432 future that could cause adverse side effects for this code.
4434 It is recommended that you look for a `new` function or equivalent in the
4435 crate's documentation.
4439 This error indicates that there is a mismatch between generic parameters and
4440 impl Trait parameters in a trait declaration versus its impl.
4442 ```compile_fail,E0643
4444 fn foo(&self, _: &impl Iterator);
4447 fn foo<U: Iterator>(&self, _: &U) { } // error method `foo` has incompatible
4448 // signature for trait
4454 It is not possible to define `main` with a where clause.
4455 Erroneous code example:
4457 ```compile_fail,E0646
4458 fn main() where i32: Copy { // error: main function is not allowed to have
4465 It is not possible to define `start` with a where clause.
4466 Erroneous code example:
4468 ```compile_fail,E0647
4472 fn start(_: isize, _: *const *const u8) -> isize where (): Copy {
4473 //^ error: start function is not allowed to have a where clause
4480 `export_name` attributes may not contain null characters (`\0`).
4482 ```compile_fail,E0648
4483 #[export_name="\0foo"] // error: `export_name` may not contain null characters
4489 This error indicates that the numeric value for the method being passed exists
4490 but the type of the numeric value or binding could not be identified.
4492 The error happens on numeric literals:
4494 ```compile_fail,E0689
4498 and on numeric bindings without an identified concrete type:
4500 ```compile_fail,E0689
4502 x.neg(); // same error as above
4505 Because of this, you must give the numeric literal or binding a type:
4510 let _ = 2.0_f32.neg();
4513 let _ = (2.0 as f32).neg();
4518 A struct with the representation hint `repr(transparent)` had zero or more than
4519 one fields that were not guaranteed to be zero-sized.
4521 Erroneous code example:
4523 ```compile_fail,E0690
4524 #[repr(transparent)]
4525 struct LengthWithUnit<U> { // error: transparent struct needs exactly one
4526 value: f32, // non-zero-sized field, but has 2
4531 Because transparent structs are represented exactly like one of their fields at
4532 run time, said field must be uniquely determined. If there is no field, or if
4533 there are multiple fields, it is not clear how the struct should be represented.
4534 Note that fields of zero-typed types (e.g., `PhantomData`) can also exist
4535 alongside the field that contains the actual data, they do not count for this
4536 error. When generic types are involved (as in the above example), an error is
4537 reported because the type parameter could be non-zero-sized.
4539 To combine `repr(transparent)` with type parameters, `PhantomData` may be
4543 use std::marker::PhantomData;
4545 #[repr(transparent)]
4546 struct LengthWithUnit<U> {
4548 unit: PhantomData<U>,
4554 A struct, enum, or union with the `repr(transparent)` representation hint
4555 contains a zero-sized field that requires non-trivial alignment.
4557 Erroneous code example:
4559 ```compile_fail,E0691
4560 #![feature(repr_align)]
4563 struct ForceAlign32;
4565 #[repr(transparent)]
4566 struct Wrapper(f32, ForceAlign32); // error: zero-sized field in transparent
4567 // struct has alignment larger than 1
4570 A transparent struct, enum, or union is supposed to be represented exactly like
4571 the piece of data it contains. Zero-sized fields with different alignment
4572 requirements potentially conflict with this property. In the example above,
4573 `Wrapper` would have to be aligned to 32 bytes even though `f32` has a smaller
4574 alignment requirement.
4576 Consider removing the over-aligned zero-sized field:
4579 #[repr(transparent)]
4580 struct Wrapper(f32);
4583 Alternatively, `PhantomData<T>` has alignment 1 for all `T`, so you can use it
4584 if you need to keep the field for some reason:
4587 #![feature(repr_align)]
4589 use std::marker::PhantomData;
4592 struct ForceAlign32;
4594 #[repr(transparent)]
4595 struct Wrapper(f32, PhantomData<ForceAlign32>);
4598 Note that empty arrays `[T; 0]` have the same alignment requirement as the
4599 element type `T`. Also note that the error is conservatively reported even when
4600 the alignment of the zero-sized type is less than or equal to the data field's
4605 A method was called on a raw pointer whose inner type wasn't completely known.
4607 For example, you may have done something like:
4610 # #![deny(warnings)]
4612 let bar = foo as *const _;
4618 Here, the type of `bar` isn't known; it could be a pointer to anything. Instead,
4619 specify a type for the pointer (preferably something that makes sense for the
4620 thing you're pointing to):
4624 let bar = foo as *const i32;
4630 Even though `is_null()` exists as a method on any raw pointer, Rust shows this
4631 error because Rust allows for `self` to have arbitrary types (behind the
4632 arbitrary_self_types feature flag).
4634 This means that someone can specify such a function:
4636 ```ignore (cannot-doctest-feature-doesnt-exist-yet)
4638 fn is_null(self: *const Self) -> bool {
4639 // do something else
4644 and now when you call `.is_null()` on a raw pointer to `Foo`, there's ambiguity.
4646 Given that we don't know what type the pointer is, and there's potential
4647 ambiguity for some types, we disallow calling methods on raw pointers when
4648 the type is unknown.
4652 A `#[marker]` trait contained an associated item.
4654 The items of marker traits cannot be overridden, so there's no need to have them
4655 when they cannot be changed per-type anyway. If you wanted them for ergonomic
4656 reasons, consider making an extension trait instead.
4660 An `impl` for a `#[marker]` trait tried to override an associated item.
4662 Because marker traits are allowed to have multiple implementations for the same
4663 type, it's not allowed to override anything in those implementations, as it
4664 would be ambiguous which override should actually be used.
4669 An `impl Trait` type expands to a recursive type.
4671 An `impl Trait` type must be expandable to a concrete type that contains no
4672 `impl Trait` types. For example the following example tries to create an
4673 `impl Trait` type `T` that is equal to `[T, T]`:
4675 ```compile_fail,E0720
4676 fn make_recursive_type() -> impl Sized {
4677 [make_recursive_type(), make_recursive_type()]
4683 An array without a fixed length was pattern-matched.
4685 Example of erroneous code:
4687 ```compile_fail,E0730
4688 #![feature(const_generics)]
4690 fn is_123<const N: usize>(x: [u32; N]) -> bool {
4692 [1, 2, 3] => true, // error: cannot pattern-match on an
4693 // array without a fixed length
4699 Ensure that the pattern is consistent with the size of the matched
4700 array. Additional elements can be matched with `..`:
4703 #![feature(slice_patterns)]
4705 let r = &[1, 2, 3, 4];
4707 &[a, b, ..] => { // ok!
4708 println!("a={}, b={}", a, b);
4715 An enum with the representation hint `repr(transparent)` had zero or more than
4718 Erroneous code example:
4720 ```compile_fail,E0731
4721 #[repr(transparent)]
4722 enum Status { // error: transparent enum needs exactly one variant, but has 2
4728 Because transparent enums are represented exactly like one of their variants at
4729 run time, said variant must be uniquely determined. If there is no variant, or
4730 if there are multiple variants, it is not clear how the enum should be
4735 An `enum` with a discriminant must specify a `#[repr(inttype)]`.
4737 A `#[repr(inttype)]` must be provided on an `enum` if it has a non-unit
4738 variant with a discriminant, or where there are both unit variants with
4739 discriminants and non-unit variants. This restriction ensures that there
4740 is a well-defined way to extract a variant's discriminant from a value;
4744 #![feature(arbitrary_enum_discriminant)]
4756 fn discriminant(v : &Enum) -> u8 {
4757 unsafe { *(v as *const Enum as *const u8) }
4760 assert_eq!(3, discriminant(&Enum::Unit));
4761 assert_eq!(2, discriminant(&Enum::Tuple(5)));
4762 assert_eq!(1, discriminant(&Enum::Struct{a: 7, b: 11}));
4767 Recursion in an `async fn` requires boxing. For example, this will not compile:
4769 ```edition2018,compile_fail,E0733
4770 #![feature(async_await)]
4771 async fn foo(n: usize) {
4778 To achieve async recursion, the `async fn` needs to be desugared
4779 such that the `Future` is explicit in the return type:
4781 ```edition2018,compile_fail,E0720
4782 # #![feature(async_await)]
4783 use std::future::Future;
4784 fn foo_desugered(n: usize) -> impl Future<Output = ()> {
4787 foo_desugered(n - 1).await;
4793 Finally, the future is wrapped in a pinned box:
4796 # #![feature(async_await)]
4797 use std::future::Future;
4799 fn foo_recursive(n: usize) -> Pin<Box<dyn Future<Output = ()>>> {
4800 Box::pin(async move {
4802 foo_recursive(n - 1).await;
4808 The `Box<...>` ensures that the result is of known size,
4809 and the pin is required to keep it in the same place in memory.
4812 } // (end of detailed error messages)
4814 register_diagnostics! {
4815 // E0035, merged into E0087/E0089
4816 // E0036, merged into E0087/E0089
4822 // E0122, // bounds in type aliases are ignored, turned into proper lint
4827 // E0159, // use of trait `{}` as struct constructor
4828 // E0163, // merged into E0071
4831 // E0172, // non-trait found in a type sum, moved to resolve
4832 // E0173, // manual implementations of unboxed closure traits are experimental
4834 // E0182, // merged into E0229
4836 // E0187, // can't infer the kind of the closure
4837 // E0188, // can not cast an immutable reference to a mutable pointer
4838 // E0189, // deprecated: can only cast a boxed pointer to a boxed object
4839 // E0190, // deprecated: can only cast a &-pointer to an &-object
4840 // E0196, // cannot determine a type for this closure
4841 E0203, // type parameter has more than one relaxed default bound,
4842 // and only one is supported
4844 // E0209, // builtin traits can only be implemented on structs or enums
4845 E0212, // cannot extract an associated type from a higher-ranked trait bound
4846 // E0213, // associated types are not accepted in this context
4847 // E0215, // angle-bracket notation is not stable with `Fn`
4848 // E0216, // parenthetical notation is only stable with `Fn`
4849 // E0217, // ambiguous associated type, defined in multiple supertraits
4850 // E0218, // no associated type defined
4851 // E0219, // associated type defined in higher-ranked supertrait
4852 // E0222, // Error code E0045 (variadic function must have C or cdecl calling
4853 // convention) duplicate
4854 E0224, // at least one non-builtin train is required for an object type
4855 E0227, // ambiguous lifetime bound, explicit lifetime bound required
4856 E0228, // explicit lifetime bound required
4859 // E0235, // structure constructor specifies a structure of type but
4860 // E0236, // no lang item for range syntax
4861 // E0237, // no lang item for range syntax
4862 // E0238, // parenthesized parameters may only be used with a trait
4863 // E0239, // `next` method of `Iterator` trait has unexpected type
4867 // E0245, // not a trait
4868 // E0246, // invalid recursive type
4870 // E0248, // value used as a type, now reported earlier during resolution as E0412
4872 E0307, // invalid method `self` type
4873 // E0319, // trait impls for defaulted traits allowed just for structs/enums
4874 // E0372, // coherence not object safe
4875 E0377, // the trait `CoerceUnsized` may only be implemented for a coercion
4876 // between structures with the same definition
4877 // E0558, // replaced with a generic attribute input check
4878 E0533, // `{}` does not name a unit variant, unit struct or a constant
4879 // E0563, // cannot determine a type for this `impl Trait`: {} // removed in 6383de15
4880 E0564, // only named lifetimes are allowed in `impl Trait`,
4881 // but `{}` was found in the type `{}`
4882 E0587, // type has conflicting packed and align representation hints
4883 E0588, // packed type cannot transitively contain a `[repr(align)]` type
4884 // E0611, // merged into E0616
4885 // E0612, // merged into E0609
4886 // E0613, // Removed (merged with E0609)
4887 E0627, // yield statement outside of generator literal
4888 E0632, // cannot provide explicit type parameters when `impl Trait` is used in
4889 // argument position.
4890 E0634, // type has conflicting packed representaton hints
4891 E0640, // infer outlives requirements
4892 E0641, // cannot cast to/from a pointer with an unknown kind
4893 E0645, // trait aliases not finished
4894 E0719, // duplicate values for associated type binding
4895 E0722, // Malformed `#[optimize]` attribute
4896 E0724, // `#[ffi_returns_twice]` is only allowed in foreign functions