1 // ignore-tidy-linelength
2 #![allow(non_snake_case)]
4 register_long_diagnostics! {
7 A pattern used to match against an enum variant must provide a sub-pattern for
8 each field of the enum variant. This error indicates that a pattern attempted to
9 extract an incorrect number of fields from a variant.
13 Apple(String, String),
18 Here the `Apple` variant has two fields, and should be matched against like so:
22 Apple(String, String),
26 let x = Fruit::Apple(String::new(), String::new());
30 Fruit::Apple(a, b) => {},
35 Matching with the wrong number of fields has no sensible interpretation:
39 Apple(String, String),
43 let x = Fruit::Apple(String::new(), String::new());
47 Fruit::Apple(a) => {},
48 Fruit::Apple(a, b, c) => {},
52 Check how many fields the enum was declared with and ensure that your pattern
57 Each field of a struct can only be bound once in a pattern. Erroneous code
67 let x = Foo { a:1, b:2 };
69 let Foo { a: x, a: y } = x;
70 // error: field `a` bound multiple times in the pattern
74 Each occurrence of a field name binds the value of that field, so to fix this
75 error you will have to remove or alter the duplicate uses of the field name.
76 Perhaps you misspelled another field name? Example:
85 let x = Foo { a:1, b:2 };
87 let Foo { a: x, b: y } = x; // ok!
93 This error indicates that a struct pattern attempted to extract a non-existent
94 field from a struct. Struct fields are identified by the name used before the
95 colon `:` so struct patterns should resemble the declaration of the struct type
105 let thing = Thing { x: 1, y: 2 };
108 Thing { x: xfield, y: yfield } => {}
112 If you are using shorthand field patterns but want to refer to the struct field
113 by a different name, you should rename it explicitly.
117 ```compile_fail,E0026
123 let thing = Thing { x: 0, y: 0 };
138 let thing = Thing { x: 0, y: 0 };
141 Thing { x, y: z } => {}
147 This error indicates that a pattern for a struct fails to specify a sub-pattern
148 for every one of the struct's fields. Ensure that each field from the struct's
149 definition is mentioned in the pattern, or use `..` to ignore unwanted fields.
153 ```compile_fail,E0027
159 let d = Dog { name: "Rusty".to_string(), age: 8 };
161 // This is incorrect.
167 This is correct (explicit):
175 let d = Dog { name: "Rusty".to_string(), age: 8 };
178 Dog { name: ref n, age: x } => {}
181 // This is also correct (ignore unused fields).
183 Dog { age: x, .. } => {}
189 In a match expression, only numbers and characters can be matched against a
190 range. This is because the compiler checks that the range is non-empty at
191 compile-time, and is unable to evaluate arbitrary comparison functions. If you
192 want to capture values of an orderable type between two end-points, you can use
195 ```compile_fail,E0029
196 let string = "salutations !";
198 // The ordering relation for strings can't be evaluated at compile time,
199 // so this doesn't work:
201 "hello" ..= "world" => {}
205 // This is a more general version, using a guard:
207 s if s >= "hello" && s <= "world" => {}
214 This error indicates that a pointer to a trait type cannot be implicitly
215 dereferenced by a pattern. Every trait defines a type, but because the
216 size of trait implementors isn't fixed, this type has no compile-time size.
217 Therefore, all accesses to trait types must be through pointers. If you
218 encounter this error you should try to avoid dereferencing the pointer.
220 ```compile_fail,E0033
221 # trait SomeTrait { fn method_one(&self){} fn method_two(&self){} }
222 # impl<T> SomeTrait for T {}
223 let trait_obj: &SomeTrait = &"some_value";
225 // This tries to implicitly dereference to create an unsized local variable.
226 let &invalid = trait_obj;
228 // You can call methods without binding to the value being pointed at.
229 trait_obj.method_one();
230 trait_obj.method_two();
233 You can read more about trait objects in the [Trait Objects] section of the
236 [Trait Objects]: https://doc.rust-lang.org/reference/types.html#trait-objects
240 The compiler doesn't know what method to call because more than one method
241 has the same prototype. Erroneous code example:
243 ```compile_fail,E0034
254 impl Trait1 for Test { fn foo() {} }
255 impl Trait2 for Test { fn foo() {} }
258 Test::foo() // error, which foo() to call?
262 To avoid this error, you have to keep only one of them and remove the others.
263 So let's take our example and fix it:
272 impl Trait1 for Test { fn foo() {} }
275 Test::foo() // and now that's good!
279 However, a better solution would be using fully explicit naming of type and
293 impl Trait1 for Test { fn foo() {} }
294 impl Trait2 for Test { fn foo() {} }
297 <Test as Trait1>::foo()
314 impl F for X { fn m(&self) { println!("I am F"); } }
315 impl G for X { fn m(&self) { println!("I am G"); } }
320 F::m(&f); // it displays "I am F"
321 G::m(&f); // it displays "I am G"
327 It is not allowed to manually call destructors in Rust. It is also not
328 necessary to do this since `drop` is called automatically whenever a value goes
331 Here's an example of this error:
333 ```compile_fail,E0040
345 let mut x = Foo { x: -7 };
346 x.drop(); // error: explicit use of destructor method
352 You can't use type or const parameters on foreign items.
353 Example of erroneous code:
355 ```compile_fail,E0044
356 extern { fn some_func<T>(x: T); }
359 To fix this, replace the generic parameter with the specializations that you
363 extern { fn some_func_i32(x: i32); }
364 extern { fn some_func_i64(x: i64); }
369 Rust only supports variadic parameters for interoperability with C code in its
370 FFI. As such, variadic parameters can only be used with functions which are
371 using the C ABI. Examples of erroneous code:
374 #![feature(unboxed_closures)]
376 extern "rust-call" { fn foo(x: u8, ...); }
380 fn foo(x: u8, ...) {}
383 To fix such code, put them in an extern "C" block:
393 Items are missing in a trait implementation. Erroneous code example:
395 ```compile_fail,E0046
403 // error: not all trait items implemented, missing: `foo`
406 When trying to make some type implement a trait `Foo`, you must, at minimum,
407 provide implementations for all of `Foo`'s required methods (meaning the
408 methods that do not have default implementations), as well as any required
409 trait items like associated types or constants. Example:
425 This error indicates that an attempted implementation of a trait method
426 has the wrong number of type or const parameters.
428 For example, the trait below has a method `foo` with a type parameter `T`,
429 but the implementation of `foo` for the type `Bar` is missing this parameter:
431 ```compile_fail,E0049
433 fn foo<T: Default>(x: T) -> Self;
438 // error: method `foo` has 0 type parameters but its trait declaration has 1
441 fn foo(x: bool) -> Self { Bar }
447 This error indicates that an attempted implementation of a trait method
448 has the wrong number of function parameters.
450 For example, the trait below has a method `foo` with two function parameters
451 (`&self` and `u8`), but the implementation of `foo` for the type `Bar` omits
454 ```compile_fail,E0050
456 fn foo(&self, x: u8) -> bool;
461 // error: method `foo` has 1 parameter but the declaration in trait `Foo::foo`
464 fn foo(&self) -> bool { true }
470 The parameters of any trait method must match between a trait implementation
471 and the trait definition.
473 Here are a couple examples of this error:
475 ```compile_fail,E0053
484 // error, expected u16, found i16
487 // error, types differ in mutability
488 fn bar(&mut self) { }
494 It is not allowed to cast to a bool. If you are trying to cast a numeric type
495 to a bool, you can compare it with zero instead:
497 ```compile_fail,E0054
500 // Not allowed, won't compile
501 let x_is_nonzero = x as bool;
508 let x_is_nonzero = x != 0;
513 During a method call, a value is automatically dereferenced as many times as
514 needed to make the value's type match the method's receiver. The catch is that
515 the compiler will only attempt to dereference a number of times up to the
516 recursion limit (which can be set via the `recursion_limit` attribute).
518 For a somewhat artificial example:
520 ```compile_fail,E0055
521 #![recursion_limit="5"]
531 let ref_foo = &&&&&Foo;
533 // error, reached the recursion limit while auto-dereferencing `&&&&&Foo`
538 One fix may be to increase the recursion limit. Note that it is possible to
539 create an infinite recursion of dereferencing, in which case the only fix is to
540 somehow break the recursion.
544 When invoking closures or other implementations of the function traits `Fn`,
545 `FnMut` or `FnOnce` using call notation, the number of parameters passed to the
546 function must match its definition.
548 An example using a closure:
550 ```compile_fail,E0057
552 let a = f(); // invalid, too few parameters
553 let b = f(4); // this works!
554 let c = f(2, 3); // invalid, too many parameters
557 A generic function must be treated similarly:
560 fn foo<F: Fn()>(f: F) {
561 f(); // this is valid, but f(3) would not work
567 The built-in function traits are generic over a tuple of the function arguments.
568 If one uses angle-bracket notation (`Fn<(T,), Output=U>`) instead of parentheses
569 (`Fn(T) -> U`) to denote the function trait, the type parameter should be a
570 tuple. Otherwise function call notation cannot be used and the trait will not be
571 implemented by closures.
573 The most likely source of this error is using angle-bracket notation without
574 wrapping the function argument type into a tuple, for example:
576 ```compile_fail,E0059
577 #![feature(unboxed_closures)]
579 fn foo<F: Fn<i32>>(f: F) -> F::Output { f(3) }
582 It can be fixed by adjusting the trait bound like this:
585 #![feature(unboxed_closures)]
587 fn foo<F: Fn<(i32,)>>(f: F) -> F::Output { f(3) }
590 Note that `(T,)` always denotes the type of a 1-tuple containing an element of
591 type `T`. The comma is necessary for syntactic disambiguation.
595 External C functions are allowed to be variadic. However, a variadic function
596 takes a minimum number of arguments. For example, consider C's variadic `printf`
600 use std::os::raw::{c_char, c_int};
603 fn printf(_: *const c_char, ...) -> c_int;
607 Using this declaration, it must be called with at least one argument, so
608 simply calling `printf()` is invalid. But the following uses are allowed:
611 # #![feature(static_nobundle)]
612 # use std::os::raw::{c_char, c_int};
613 # #[cfg_attr(all(windows, target_env = "msvc"),
614 # link(name = "legacy_stdio_definitions", kind = "static-nobundle"))]
615 # extern "C" { fn printf(_: *const c_char, ...) -> c_int; }
618 use std::ffi::CString;
620 let fmt = CString::new("test\n").unwrap();
621 printf(fmt.as_ptr());
623 let fmt = CString::new("number = %d\n").unwrap();
624 printf(fmt.as_ptr(), 3);
626 let fmt = CString::new("%d, %d\n").unwrap();
627 printf(fmt.as_ptr(), 10, 5);
632 // ^ Note: On MSVC 2015, the `printf` function is "inlined" in the C code, and
633 // the C runtime does not contain the `printf` definition. This leads to linker
634 // error from the doc test (issue #42830).
635 // This can be fixed by linking to the static library
636 // `legacy_stdio_definitions.lib` (see https://stackoverflow.com/a/36504365/).
637 // If this compatibility library is removed in the future, consider changing
638 // `printf` in this example to another well-known variadic function.
641 The number of arguments passed to a function must match the number of arguments
642 specified in the function signature.
644 For example, a function like:
647 fn f(a: u16, b: &str) {}
650 Must always be called with exactly two arguments, e.g., `f(2, "test")`.
652 Note that Rust does not have a notion of optional function arguments or
653 variadic functions (except for its C-FFI).
657 This error indicates that during an attempt to build a struct or struct-like
658 enum variant, one of the fields was specified more than once. Erroneous code
661 ```compile_fail,E0062
669 x: 0, // error: field `x` specified more than once
674 Each field should be specified exactly one time. Example:
682 let x = Foo { x: 0 }; // ok!
688 This error indicates that during an attempt to build a struct or struct-like
689 enum variant, one of the fields was not provided. Erroneous code example:
691 ```compile_fail,E0063
698 let x = Foo { x: 0 }; // error: missing field: `y`
702 Each field should be specified exactly once. Example:
711 let x = Foo { x: 0, y: 0 }; // ok!
717 The left-hand side of a compound assignment expression must be a place
718 expression. A place expression represents a memory location and includes
719 item paths (ie, namespaced variables), dereferences, indexing expressions,
720 and field references.
722 Let's start with some erroneous code examples:
724 ```compile_fail,E0067
725 use std::collections::LinkedList;
727 // Bad: assignment to non-place expression
728 LinkedList::new() += 1;
732 fn some_func(i: &mut i32) {
733 i += 12; // Error : '+=' operation cannot be applied on a reference !
737 And now some working examples:
746 fn some_func(i: &mut i32) {
753 The compiler found a function whose body contains a `return;` statement but
754 whose return type is not `()`. An example of this is:
756 ```compile_fail,E0069
763 Since `return;` is just like `return ();`, there is a mismatch between the
764 function's return type and the value being returned.
768 The left-hand side of an assignment operator must be a place expression. A
769 place expression represents a memory location and can be a variable (with
770 optional namespacing), a dereference, an indexing expression or a field
773 More details can be found in the [Expressions] section of the Reference.
775 [Expressions]: https://doc.rust-lang.org/reference/expressions.html#places-rvalues-and-temporaries
777 Now, we can go further. Here are some erroneous code examples:
779 ```compile_fail,E0070
785 const SOME_CONST : i32 = 12;
787 fn some_other_func() {}
790 SOME_CONST = 14; // error : a constant value cannot be changed!
791 1 = 3; // error : 1 isn't a valid place!
792 some_other_func() = 4; // error : we can't assign value to a function!
793 SomeStruct.x = 12; // error : SomeStruct a structure name but it is used
798 And now let's give working examples:
805 let mut s = SomeStruct {x: 0, y: 0};
807 s.x = 3; // that's good !
811 fn some_func(x: &mut i32) {
812 *x = 12; // that's good !
818 You tried to use structure-literal syntax to create an item that is
819 not a structure or enum variant.
821 Example of erroneous code:
823 ```compile_fail,E0071
825 let t = U32 { value: 4 }; // error: expected struct, variant or union type,
826 // found builtin type `u32`
829 To fix this, ensure that the name was correctly spelled, and that
830 the correct form of initializer was used.
832 For example, the code above can be fixed to:
840 let u = Foo::FirstValue(0i32);
848 #### Note: this error code is no longer emitted by the compiler.
850 You cannot define a struct (or enum) `Foo` that requires an instance of `Foo`
851 in order to make a new `Foo` value. This is because there would be no way a
852 first instance of `Foo` could be made to initialize another instance!
854 Here's an example of a struct that has this problem:
857 struct Foo { x: Box<Foo> } // error
860 One fix is to use `Option`, like so:
863 struct Foo { x: Option<Box<Foo>> }
866 Now it's possible to create at least one instance of `Foo`: `Foo { x: None }`.
870 #### Note: this error code is no longer emitted by the compiler.
872 When using the `#[simd]` attribute on a tuple struct, the components of the
873 tuple struct must all be of a concrete, nongeneric type so the compiler can
874 reason about how to use SIMD with them. This error will occur if the types
877 This will cause an error:
880 #![feature(repr_simd)]
883 struct Bad<T>(T, T, T);
889 #![feature(repr_simd)]
892 struct Good(u32, u32, u32);
897 The `#[simd]` attribute can only be applied to non empty tuple structs, because
898 it doesn't make sense to try to use SIMD operations when there are no values to
901 This will cause an error:
903 ```compile_fail,E0075
904 #![feature(repr_simd)]
913 #![feature(repr_simd)]
921 When using the `#[simd]` attribute to automatically use SIMD operations in tuple
922 struct, the types in the struct must all be of the same type, or the compiler
923 will trigger this error.
925 This will cause an error:
927 ```compile_fail,E0076
928 #![feature(repr_simd)]
931 struct Bad(u16, u32, u32);
937 #![feature(repr_simd)]
940 struct Good(u32, u32, u32);
945 When using the `#[simd]` attribute on a tuple struct, the elements in the tuple
946 must be machine types so SIMD operations can be applied to them.
948 This will cause an error:
950 ```compile_fail,E0077
951 #![feature(repr_simd)]
960 #![feature(repr_simd)]
963 struct Good(u32, u32, u32);
968 Enum discriminants are used to differentiate enum variants stored in memory.
969 This error indicates that the same value was used for two or more variants,
970 making them impossible to tell apart.
972 ```compile_fail,E0081
990 Note that variants without a manually specified discriminant are numbered from
991 top to bottom starting from 0, so clashes can occur with seemingly unrelated
994 ```compile_fail,E0081
1001 Here `X` will have already been specified the discriminant 0 by the time `Y` is
1002 encountered, so a conflict occurs.
1006 An unsupported representation was attempted on a zero-variant enum.
1008 Erroneous code example:
1010 ```compile_fail,E0084
1012 enum NightsWatch {} // error: unsupported representation for zero-variant enum
1015 It is impossible to define an integer type to be used to represent zero-variant
1016 enum values because there are no zero-variant enum values. There is no way to
1017 construct an instance of the following type using only safe code. So you have
1018 two solutions. Either you add variants in your enum:
1028 or you remove the integer represention of your enum:
1035 // FIXME(const_generics:docs): example of inferring const parameter.
1037 #### Note: this error code is no longer emitted by the compiler.
1039 Too many type arguments were supplied for a function. For example:
1041 ```compile_fail,E0107
1045 foo::<f64, bool>(); // error: wrong number of type arguments:
1046 // expected 1, found 2
1050 The number of supplied arguments must exactly match the number of defined type
1055 #### Note: this error code is no longer emitted by the compiler.
1057 You gave too many lifetime arguments. Erroneous code example:
1059 ```compile_fail,E0107
1063 f::<'static>() // error: wrong number of lifetime arguments:
1064 // expected 0, found 1
1068 Please check you give the right number of lifetime arguments. Example:
1078 It's also important to note that the Rust compiler can generally
1079 determine the lifetime by itself. Example:
1087 // it can be written like this
1088 fn get_value<'a>(&'a self) -> &'a str { &self.value }
1089 // but the compiler works fine with this too:
1090 fn without_lifetime(&self) -> &str { &self.value }
1094 let f = Foo { value: "hello".to_owned() };
1096 println!("{}", f.get_value());
1097 println!("{}", f.without_lifetime());
1103 #### Note: this error code is no longer emitted by the compiler.
1105 Too few type arguments were supplied for a function. For example:
1107 ```compile_fail,E0107
1111 foo::<f64>(); // error: wrong number of type arguments: expected 2, found 1
1115 Note that if a function takes multiple type arguments but you want the compiler
1116 to infer some of them, you can use type placeholders:
1118 ```compile_fail,E0107
1119 fn foo<T, U>(x: T) {}
1123 foo::<f64>(x); // error: wrong number of type arguments:
1124 // expected 2, found 1
1125 foo::<_, f64>(x); // same as `foo::<bool, f64>(x)`
1131 #### Note: this error code is no longer emitted by the compiler.
1133 You gave too few lifetime arguments. Example:
1135 ```compile_fail,E0107
1136 fn foo<'a: 'b, 'b: 'a>() {}
1139 foo::<'static>(); // error: wrong number of lifetime arguments:
1140 // expected 2, found 1
1144 Please check you give the right number of lifetime arguments. Example:
1147 fn foo<'a: 'b, 'b: 'a>() {}
1150 foo::<'static, 'static>();
1156 You gave an unnecessary type or const parameter in a type alias. Erroneous
1159 ```compile_fail,E0091
1160 type Foo<T> = u32; // error: type parameter `T` is unused
1162 type Foo<A,B> = Box<A>; // error: type parameter `B` is unused
1165 Please check you didn't write too many parameters. Example:
1168 type Foo = u32; // ok!
1169 type Foo2<A> = Box<A>; // ok!
1174 You tried to declare an undefined atomic operation function.
1175 Erroneous code example:
1177 ```compile_fail,E0092
1178 #![feature(intrinsics)]
1180 extern "rust-intrinsic" {
1181 fn atomic_foo(); // error: unrecognized atomic operation
1186 Please check you didn't make a mistake in the function's name. All intrinsic
1187 functions are defined in librustc_codegen_llvm/intrinsic.rs and in
1188 libcore/intrinsics.rs in the Rust source code. Example:
1191 #![feature(intrinsics)]
1193 extern "rust-intrinsic" {
1194 fn atomic_fence(); // ok!
1200 You declared an unknown intrinsic function. Erroneous code example:
1202 ```compile_fail,E0093
1203 #![feature(intrinsics)]
1205 extern "rust-intrinsic" {
1206 fn foo(); // error: unrecognized intrinsic function: `foo`
1216 Please check you didn't make a mistake in the function's name. All intrinsic
1217 functions are defined in librustc_codegen_llvm/intrinsic.rs and in
1218 libcore/intrinsics.rs in the Rust source code. Example:
1221 #![feature(intrinsics)]
1223 extern "rust-intrinsic" {
1224 fn atomic_fence(); // ok!
1236 You gave an invalid number of type parameters to an intrinsic function.
1237 Erroneous code example:
1239 ```compile_fail,E0094
1240 #![feature(intrinsics)]
1242 extern "rust-intrinsic" {
1243 fn size_of<T, U>() -> usize; // error: intrinsic has wrong number
1244 // of type parameters
1248 Please check that you provided the right number of type parameters
1249 and verify with the function declaration in the Rust source code.
1253 #![feature(intrinsics)]
1255 extern "rust-intrinsic" {
1256 fn size_of<T>() -> usize; // ok!
1262 This error means that an incorrect number of generic arguments were provided:
1264 ```compile_fail,E0107
1265 struct Foo<T> { x: T }
1267 struct Bar { x: Foo } // error: wrong number of type arguments:
1268 // expected 1, found 0
1269 struct Baz<S, T> { x: Foo<S, T> } // error: wrong number of type arguments:
1270 // expected 1, found 2
1272 fn foo<T, U>(x: T, y: U) {}
1276 foo::<bool>(x); // error: wrong number of type arguments:
1277 // expected 2, found 1
1278 foo::<bool, i32, i32>(x, 2, 4); // error: wrong number of type arguments:
1279 // expected 2, found 3
1285 f::<'static>(); // error: wrong number of lifetime arguments:
1286 // expected 0, found 1
1293 You tried to provide a generic argument to a type which doesn't need it.
1294 Erroneous code example:
1296 ```compile_fail,E0109
1297 type X = u32<i32>; // error: type arguments are not allowed for this type
1298 type Y = bool<'static>; // error: lifetime parameters are not allowed on
1302 Check that you used the correct argument and that the definition is correct.
1307 type X = u32; // ok!
1308 type Y = bool; // ok!
1311 Note that generic arguments for enum variant constructors go after the variant,
1312 not after the enum. For example, you would write `Option::None::<u32>`,
1313 rather than `Option::<u32>::None`.
1317 #### Note: this error code is no longer emitted by the compiler.
1319 You tried to provide a lifetime to a type which doesn't need it.
1320 See `E0109` for more details.
1324 You can only define an inherent implementation for a type in the same crate
1325 where the type was defined. For example, an `impl` block as below is not allowed
1326 since `Vec` is defined in the standard library:
1328 ```compile_fail,E0116
1329 impl Vec<u8> { } // error
1332 To fix this problem, you can do either of these things:
1334 - define a trait that has the desired associated functions/types/constants and
1335 implement the trait for the type in question
1336 - define a new type wrapping the type and define an implementation on the new
1339 Note that using the `type` keyword does not work here because `type` only
1340 introduces a type alias:
1342 ```compile_fail,E0116
1343 type Bytes = Vec<u8>;
1345 impl Bytes { } // error, same as above
1350 This error indicates a violation of one of Rust's orphan rules for trait
1351 implementations. The rule prohibits any implementation of a foreign trait (a
1352 trait defined in another crate) where
1354 - the type that is implementing the trait is foreign
1355 - all of the parameters being passed to the trait (if there are any) are also
1358 Here's one example of this error:
1360 ```compile_fail,E0117
1361 impl Drop for u32 {}
1364 To avoid this kind of error, ensure that at least one local type is referenced
1368 pub struct Foo; // you define your type in your crate
1370 impl Drop for Foo { // and you can implement the trait on it!
1371 // code of trait implementation here
1372 # fn drop(&mut self) { }
1375 impl From<Foo> for i32 { // or you use a type from your crate as
1377 fn from(i: Foo) -> i32 {
1383 Alternatively, define a trait locally and implement that instead:
1387 fn get(&self) -> usize;
1391 fn get(&self) -> usize { 0 }
1395 For information on the design of the orphan rules, see [RFC 1023].
1397 [RFC 1023]: https://github.com/rust-lang/rfcs/blob/master/text/1023-rebalancing-coherence.md
1401 You're trying to write an inherent implementation for something which isn't a
1402 struct nor an enum. Erroneous code example:
1404 ```compile_fail,E0118
1405 impl (u8, u8) { // error: no base type found for inherent implementation
1406 fn get_state(&self) -> String {
1412 To fix this error, please implement a trait on the type or wrap it in a struct.
1416 // we create a trait here
1417 trait LiveLongAndProsper {
1418 fn get_state(&self) -> String;
1421 // and now you can implement it on (u8, u8)
1422 impl LiveLongAndProsper for (u8, u8) {
1423 fn get_state(&self) -> String {
1424 "He's dead, Jim!".to_owned()
1429 Alternatively, you can create a newtype. A newtype is a wrapping tuple-struct.
1430 For example, `NewType` is a newtype over `Foo` in `struct NewType(Foo)`.
1434 struct TypeWrapper((u8, u8));
1437 fn get_state(&self) -> String {
1438 "Fascinating!".to_owned()
1445 An attempt was made to implement Drop on a trait, which is not allowed: only
1446 structs and enums can implement Drop. An example causing this error:
1448 ```compile_fail,E0120
1451 impl Drop for MyTrait {
1452 fn drop(&mut self) {}
1456 A workaround for this problem is to wrap the trait up in a struct, and implement
1457 Drop on that. An example is shown below:
1461 struct MyWrapper<T: MyTrait> { foo: T }
1463 impl <T: MyTrait> Drop for MyWrapper<T> {
1464 fn drop(&mut self) {}
1469 Alternatively, wrapping trait objects requires something like the following:
1474 //or Box<MyTrait>, if you wanted an owned trait object
1475 struct MyWrapper<'a> { foo: &'a MyTrait }
1477 impl <'a> Drop for MyWrapper<'a> {
1478 fn drop(&mut self) {}
1484 In order to be consistent with Rust's lack of global type inference, type
1485 placeholders are disallowed by design in item signatures.
1487 Examples of this error include:
1489 ```compile_fail,E0121
1490 fn foo() -> _ { 5 } // error, explicitly write out the return type instead
1492 static BAR: _ = "test"; // error, explicitly write out the type instead
1497 You declared two fields of a struct with the same name. Erroneous code
1500 ```compile_fail,E0124
1503 field1: i32, // error: field is already declared
1507 Please verify that the field names have been correctly spelled. Example:
1518 It is not possible to define `main` with generic parameters.
1519 When `main` is present, it must take no arguments and return `()`.
1520 Erroneous code example:
1522 ```compile_fail,E0131
1523 fn main<T>() { // error: main function is not allowed to have generic parameters
1529 A function with the `start` attribute was declared with type parameters.
1531 Erroneous code example:
1533 ```compile_fail,E0132
1540 It is not possible to declare type parameters on a function that has the `start`
1541 attribute. Such a function must have the following type signature (for more
1542 information, view [the unstable book][1]):
1544 [1]: https://doc.rust-lang.org/unstable-book/language-features/lang-items.html#writing-an-executable-without-stdlib
1548 fn(isize, *const *const u8) -> isize;
1557 fn my_start(argc: isize, argv: *const *const u8) -> isize {
1564 This error means that an attempt was made to match a struct type enum
1565 variant as a non-struct type:
1567 ```compile_fail,E0164
1568 enum Foo { B { i: u32 } }
1570 fn bar(foo: Foo) -> u32 {
1572 Foo::B(i) => i, // error E0164
1577 Try using `{}` instead:
1580 enum Foo { B { i: u32 } }
1582 fn bar(foo: Foo) -> u32 {
1591 Explicitly implementing both Drop and Copy for a type is currently disallowed.
1592 This feature can make some sense in theory, but the current implementation is
1593 incorrect and can lead to memory unsafety (see [issue #20126][iss20126]), so
1594 it has been disabled for now.
1596 [iss20126]: https://github.com/rust-lang/rust/issues/20126
1600 An associated function for a trait was defined to be static, but an
1601 implementation of the trait declared the same function to be a method (i.e., to
1602 take a `self` parameter).
1604 Here's an example of this error:
1606 ```compile_fail,E0185
1614 // error, method `foo` has a `&self` declaration in the impl, but not in
1622 An associated function for a trait was defined to be a method (i.e., to take a
1623 `self` parameter), but an implementation of the trait declared the same function
1626 Here's an example of this error:
1628 ```compile_fail,E0186
1636 // error, method `foo` has a `&self` declaration in the trait, but not in
1644 Trait objects need to have all associated types specified. Erroneous code
1647 ```compile_fail,E0191
1652 type Foo = Trait; // error: the value of the associated type `Bar` (from
1653 // the trait `Trait`) must be specified
1656 Please verify you specified all associated types of the trait and that you
1657 used the right trait. Example:
1664 type Foo = Trait<Bar=i32>; // ok!
1669 Negative impls are only allowed for auto traits. For more
1670 information see the [opt-in builtin traits RFC][RFC 19].
1672 [RFC 19]: https://github.com/rust-lang/rfcs/blob/master/text/0019-opt-in-builtin-traits.md
1676 #### Note: this error code is no longer emitted by the compiler.
1678 `where` clauses must use generic type parameters: it does not make sense to use
1679 them otherwise. An example causing this error:
1686 #[derive(Copy,Clone)]
1691 impl Foo for Wrapper<u32> where Wrapper<u32>: Clone {
1696 This use of a `where` clause is strange - a more common usage would look
1697 something like the following:
1704 #[derive(Copy,Clone)]
1708 impl <T> Foo for Wrapper<T> where Wrapper<T>: Clone {
1713 Here, we're saying that the implementation exists on Wrapper only when the
1714 wrapped type `T` implements `Clone`. The `where` clause is important because
1715 some types will not implement `Clone`, and thus will not get this method.
1717 In our erroneous example, however, we're referencing a single concrete type.
1718 Since we know for certain that `Wrapper<u32>` implements `Clone`, there's no
1719 reason to also specify it in a `where` clause.
1723 A type parameter was declared which shadows an existing one. An example of this
1726 ```compile_fail,E0194
1728 fn do_something(&self) -> T;
1729 fn do_something_else<T: Clone>(&self, bar: T);
1733 In this example, the trait `Foo` and the trait method `do_something_else` both
1734 define a type parameter `T`. This is not allowed: if the method wishes to
1735 define a type parameter, it must use a different name for it.
1739 Your method's lifetime parameters do not match the trait declaration.
1740 Erroneous code example:
1742 ```compile_fail,E0195
1744 fn bar<'a,'b:'a>(x: &'a str, y: &'b str);
1749 impl Trait for Foo {
1750 fn bar<'a,'b>(x: &'a str, y: &'b str) {
1751 // error: lifetime parameters or bounds on method `bar`
1752 // do not match the trait declaration
1757 The lifetime constraint `'b` for bar() implementation does not match the
1758 trait declaration. Ensure lifetime declarations match exactly in both trait
1759 declaration and implementation. Example:
1763 fn t<'a,'b:'a>(x: &'a str, y: &'b str);
1768 impl Trait for Foo {
1769 fn t<'a,'b:'a>(x: &'a str, y: &'b str) { // ok!
1776 Safe traits should not have unsafe implementations, therefore marking an
1777 implementation for a safe trait unsafe will cause a compiler error. Removing
1778 the unsafe marker on the trait noted in the error will resolve this problem.
1780 ```compile_fail,E0199
1785 // this won't compile because Bar is safe
1786 unsafe impl Bar for Foo { }
1787 // this will compile
1788 impl Bar for Foo { }
1793 Unsafe traits must have unsafe implementations. This error occurs when an
1794 implementation for an unsafe trait isn't marked as unsafe. This may be resolved
1795 by marking the unsafe implementation as unsafe.
1797 ```compile_fail,E0200
1800 unsafe trait Bar { }
1802 // this won't compile because Bar is unsafe and impl isn't unsafe
1803 impl Bar for Foo { }
1804 // this will compile
1805 unsafe impl Bar for Foo { }
1810 It is an error to define two associated items (like methods, associated types,
1811 associated functions, etc.) with the same identifier.
1815 ```compile_fail,E0201
1819 fn bar(&self) -> bool { self.0 > 5 }
1820 fn bar() {} // error: duplicate associated function
1825 fn baz(&self) -> bool;
1831 fn baz(&self) -> bool { true }
1833 // error: duplicate method
1834 fn baz(&self) -> bool { self.0 > 5 }
1836 // error: duplicate associated type
1841 Note, however, that items with the same name are allowed for inherent `impl`
1842 blocks that don't overlap:
1848 fn bar(&self) -> bool { self.0 > 5 }
1852 fn bar(&self) -> bool { self.0 }
1858 Inherent associated types were part of [RFC 195] but are not yet implemented.
1859 See [the tracking issue][iss8995] for the status of this implementation.
1861 [RFC 195]: https://github.com/rust-lang/rfcs/blob/master/text/0195-associated-items.md
1862 [iss8995]: https://github.com/rust-lang/rust/issues/8995
1866 An attempt to implement the `Copy` trait for a struct failed because one of the
1867 fields does not implement `Copy`. To fix this, you must implement `Copy` for the
1868 mentioned field. Note that this may not be possible, as in the example of
1870 ```compile_fail,E0204
1875 impl Copy for Foo { }
1878 This fails because `Vec<T>` does not implement `Copy` for any `T`.
1880 Here's another example that will fail:
1882 ```compile_fail,E0204
1889 This fails because `&mut T` is not `Copy`, even when `T` is `Copy` (this
1890 differs from the behavior for `&T`, which is always `Copy`).
1895 An attempt to implement the `Copy` trait for an enum failed because one of the
1896 variants does not implement `Copy`. To fix this, you must implement `Copy` for
1897 the mentioned variant. Note that this may not be possible, as in the example of
1899 ```compile_fail,E0205
1905 impl Copy for Foo { }
1908 This fails because `Vec<T>` does not implement `Copy` for any `T`.
1910 Here's another example that will fail:
1912 ```compile_fail,E0205
1920 This fails because `&mut T` is not `Copy`, even when `T` is `Copy` (this
1921 differs from the behavior for `&T`, which is always `Copy`).
1926 You can only implement `Copy` for a struct or enum. Both of the following
1927 examples will fail, because neither `[u8; 256]` nor `&'static mut Bar`
1928 (mutable reference to `Bar`) is a struct or enum:
1930 ```compile_fail,E0206
1931 type Foo = [u8; 256];
1932 impl Copy for Foo { } // error
1934 #[derive(Copy, Clone)]
1936 impl Copy for &'static mut Bar { } // error
1941 Any type parameter or lifetime parameter of an `impl` must meet at least one of
1942 the following criteria:
1944 - it appears in the self type of the impl
1945 - for a trait impl, it appears in the trait reference
1946 - it is bound as an associated type
1950 Suppose we have a struct `Foo` and we would like to define some methods for it.
1951 The following definition leads to a compiler error:
1953 ```compile_fail,E0207
1956 impl<T: Default> Foo {
1957 // error: the type parameter `T` is not constrained by the impl trait, self
1958 // type, or predicates [E0207]
1959 fn get(&self) -> T {
1960 <T as Default>::default()
1965 The problem is that the parameter `T` does not appear in the self type (`Foo`)
1966 of the impl. In this case, we can fix the error by moving the type parameter
1967 from the `impl` to the method `get`:
1973 // Move the type parameter from the impl to the method
1975 fn get<T: Default>(&self) -> T {
1976 <T as Default>::default()
1983 As another example, suppose we have a `Maker` trait and want to establish a
1984 type `FooMaker` that makes `Foo`s:
1986 ```compile_fail,E0207
1989 fn make(&mut self) -> Self::Item;
1998 impl<T: Default> Maker for FooMaker {
1999 // error: the type parameter `T` is not constrained by the impl trait, self
2000 // type, or predicates [E0207]
2003 fn make(&mut self) -> Foo<T> {
2004 Foo { foo: <T as Default>::default() }
2009 This fails to compile because `T` does not appear in the trait or in the
2012 One way to work around this is to introduce a phantom type parameter into
2013 `FooMaker`, like so:
2016 use std::marker::PhantomData;
2020 fn make(&mut self) -> Self::Item;
2027 // Add a type parameter to `FooMaker`
2028 struct FooMaker<T> {
2029 phantom: PhantomData<T>,
2032 impl<T: Default> Maker for FooMaker<T> {
2035 fn make(&mut self) -> Foo<T> {
2037 foo: <T as Default>::default(),
2043 Another way is to do away with the associated type in `Maker` and use an input
2044 type parameter instead:
2047 // Use a type parameter instead of an associated type here
2049 fn make(&mut self) -> Item;
2058 impl<T: Default> Maker<Foo<T>> for FooMaker {
2059 fn make(&mut self) -> Foo<T> {
2060 Foo { foo: <T as Default>::default() }
2065 ### Additional information
2067 For more information, please see [RFC 447].
2069 [RFC 447]: https://github.com/rust-lang/rfcs/blob/master/text/0447-no-unused-impl-parameters.md
2073 This error indicates a violation of one of Rust's orphan rules for trait
2074 implementations. The rule concerns the use of type parameters in an
2075 implementation of a foreign trait (a trait defined in another crate), and
2076 states that type parameters must be "covered" by a local type. To understand
2077 what this means, it is perhaps easiest to consider a few examples.
2079 If `ForeignTrait` is a trait defined in some external crate `foo`, then the
2080 following trait `impl` is an error:
2082 ```compile_fail,E0210
2083 # #[cfg(for_demonstration_only)]
2085 # #[cfg(for_demonstration_only)]
2086 use foo::ForeignTrait;
2087 # use std::panic::UnwindSafe as ForeignTrait;
2089 impl<T> ForeignTrait for T { } // error
2093 To work around this, it can be covered with a local type, `MyType`:
2096 # use std::panic::UnwindSafe as ForeignTrait;
2097 struct MyType<T>(T);
2098 impl<T> ForeignTrait for MyType<T> { } // Ok
2101 Please note that a type alias is not sufficient.
2103 For another example of an error, suppose there's another trait defined in `foo`
2104 named `ForeignTrait2` that takes two type parameters. Then this `impl` results
2105 in the same rule violation:
2107 ```ignore (cannot-doctest-multicrate-project)
2109 impl<T> ForeignTrait2<T, MyType<T>> for MyType2 { } // error
2112 The reason for this is that there are two appearances of type parameter `T` in
2113 the `impl` header, both as parameters for `ForeignTrait2`. The first appearance
2114 is uncovered, and so runs afoul of the orphan rule.
2116 Consider one more example:
2118 ```ignore (cannot-doctest-multicrate-project)
2119 impl<T> ForeignTrait2<MyType<T>, T> for MyType2 { } // Ok
2122 This only differs from the previous `impl` in that the parameters `T` and
2123 `MyType<T>` for `ForeignTrait2` have been swapped. This example does *not*
2124 violate the orphan rule; it is permitted.
2126 To see why that last example was allowed, you need to understand the general
2127 rule. Unfortunately this rule is a bit tricky to state. Consider an `impl`:
2129 ```ignore (only-for-syntax-highlight)
2130 impl<P1, ..., Pm> ForeignTrait<T1, ..., Tn> for T0 { ... }
2133 where `P1, ..., Pm` are the type parameters of the `impl` and `T0, ..., Tn`
2134 are types. One of the types `T0, ..., Tn` must be a local type (this is another
2135 orphan rule, see the explanation for E0117). Let `i` be the smallest integer
2136 such that `Ti` is a local type. Then no type parameter can appear in any of the
2139 For information on the design of the orphan rules, see [RFC 1023].
2141 [RFC 1023]: https://github.com/rust-lang/rfcs/blob/master/text/1023-rebalancing-coherence.md
2146 You used a function or type which doesn't fit the requirements for where it was
2147 used. Erroneous code examples:
2150 #![feature(intrinsics)]
2152 extern "rust-intrinsic" {
2153 fn size_of<T>(); // error: intrinsic has wrong type
2158 fn main() -> i32 { 0 }
2159 // error: main function expects type: `fn() {main}`: expected (), found i32
2166 // error: mismatched types in range: expected u8, found i8
2176 fn x(self: Rc<Foo>) {}
2177 // error: mismatched self type: expected `Foo`: expected struct
2178 // `Foo`, found struct `alloc::rc::Rc`
2182 For the first code example, please check the function definition. Example:
2185 #![feature(intrinsics)]
2187 extern "rust-intrinsic" {
2188 fn size_of<T>() -> usize; // ok!
2192 The second case example is a bit particular : the main function must always
2193 have this definition:
2199 They never take parameters and never return types.
2201 For the third example, when you match, all patterns must have the same type
2202 as the type you're matching on. Example:
2208 0u8..=3u8 => (), // ok!
2213 And finally, for the last example, only `Box<Self>`, `&Self`, `Self`,
2214 or `&mut Self` work as explicit self parameters. Example:
2220 fn x(self: Box<Foo>) {} // ok!
2227 You used an associated type which isn't defined in the trait.
2228 Erroneous code example:
2230 ```compile_fail,E0220
2235 type Foo = T1<F=i32>; // error: associated type `F` not found for `T1`
2242 // error: Baz is used but not declared
2243 fn return_bool(&self, _: &Self::Bar, _: &Self::Baz) -> bool;
2247 Make sure that you have defined the associated type in the trait body.
2248 Also, verify that you used the right trait or you didn't misspell the
2249 associated type name. Example:
2256 type Foo = T1<Bar=i32>; // ok!
2262 type Baz; // we declare `Baz` in our trait.
2264 // and now we can use it here:
2265 fn return_bool(&self, _: &Self::Bar, _: &Self::Baz) -> bool;
2271 An attempt was made to retrieve an associated type, but the type was ambiguous.
2274 ```compile_fail,E0221
2290 In this example, `Foo` defines an associated type `A`. `Bar` inherits that type
2291 from `Foo`, and defines another associated type of the same name. As a result,
2292 when we attempt to use `Self::A`, it's ambiguous whether we mean the `A` defined
2293 by `Foo` or the one defined by `Bar`.
2295 There are two options to work around this issue. The first is simply to rename
2296 one of the types. Alternatively, one can specify the intended type using the
2310 let _: <Self as Bar>::A;
2317 An attempt was made to retrieve an associated type, but the type was ambiguous.
2320 ```compile_fail,E0223
2321 trait MyTrait {type X; }
2324 let foo: MyTrait::X;
2328 The problem here is that we're attempting to take the type of X from MyTrait.
2329 Unfortunately, the type of X is not defined, because it's only made concrete in
2330 implementations of the trait. A working version of this code might look like:
2333 trait MyTrait {type X; }
2336 impl MyTrait for MyStruct {
2341 let foo: <MyStruct as MyTrait>::X;
2345 This syntax specifies that we want the X type from MyTrait, as made concrete in
2346 MyStruct. The reason that we cannot simply use `MyStruct::X` is that MyStruct
2347 might implement two different traits with identically-named associated types.
2348 This syntax allows disambiguation between the two.
2352 You attempted to use multiple types as bounds for a closure or trait object.
2353 Rust does not currently support this. A simple example that causes this error:
2355 ```compile_fail,E0225
2357 let _: Box<dyn std::io::Read + std::io::Write>;
2361 Auto traits such as Send and Sync are an exception to this rule:
2362 It's possible to have bounds of one non-builtin trait, plus any number of
2363 auto traits. For example, the following compiles correctly:
2367 let _: Box<dyn std::io::Read + Send + Sync>;
2373 An associated type binding was done outside of the type parameter declaration
2374 and `where` clause. Erroneous code example:
2376 ```compile_fail,E0229
2379 fn boo(&self) -> <Self as Foo>::A;
2384 impl Foo for isize {
2386 fn boo(&self) -> usize { 42 }
2389 fn baz<I>(x: &<I as Foo<A=Bar>>::A) {}
2390 // error: associated type bindings are not allowed here
2393 To solve this error, please move the type bindings in the type parameter
2398 # trait Foo { type A; }
2399 fn baz<I: Foo<A=Bar>>(x: &<I as Foo>::A) {} // ok!
2402 Or in the `where` clause:
2406 # trait Foo { type A; }
2407 fn baz<I>(x: &<I as Foo>::A) where I: Foo<A=Bar> {}
2412 #### Note: this error code is no longer emitted by the compiler.
2414 This error indicates that not enough type parameters were found in a type or
2417 For example, the `Foo` struct below is defined to be generic in `T`, but the
2418 type parameter is missing in the definition of `Bar`:
2420 ```compile_fail,E0107
2421 struct Foo<T> { x: T }
2423 struct Bar { x: Foo }
2428 #### Note: this error code is no longer emitted by the compiler.
2430 This error indicates that too many type parameters were found in a type or
2433 For example, the `Foo` struct below has no type parameters, but is supplied
2434 with two in the definition of `Bar`:
2436 ```compile_fail,E0107
2437 struct Foo { x: bool }
2439 struct Bar<S, T> { x: Foo<S, T> }
2444 A cross-crate opt-out trait was implemented on something which wasn't a struct
2445 or enum type. Erroneous code example:
2447 ```compile_fail,E0321
2448 #![feature(optin_builtin_traits)]
2452 impl !Sync for Foo {}
2454 unsafe impl Send for &'static Foo {}
2455 // error: cross-crate traits with a default impl, like `core::marker::Send`,
2456 // can only be implemented for a struct/enum type, not
2460 Only structs and enums are permitted to impl Send, Sync, and other opt-out
2461 trait, and the struct or enum must be local to the current crate. So, for
2462 example, `unsafe impl Send for Rc<Foo>` is not allowed.
2466 The `Sized` trait is a special trait built-in to the compiler for types with a
2467 constant size known at compile-time. This trait is automatically implemented
2468 for types as needed by the compiler, and it is currently disallowed to
2469 explicitly implement it for a type.
2473 An associated const was implemented when another trait item was expected.
2474 Erroneous code example:
2476 ```compile_fail,E0323
2485 // error: item `N` is an associated const, which doesn't match its
2486 // trait `<Bar as Foo>`
2490 Please verify that the associated const wasn't misspelled and the correct trait
2491 was implemented. Example:
2501 type N = u32; // ok!
2515 const N : u32 = 0; // ok!
2521 A method was implemented when another trait item was expected. Erroneous
2524 ```compile_fail,E0324
2535 // error: item `N` is an associated method, which doesn't match its
2536 // trait `<Bar as Foo>`
2540 To fix this error, please verify that the method name wasn't misspelled and
2541 verify that you are indeed implementing the correct trait items. Example:
2561 An associated type was implemented when another trait item was expected.
2562 Erroneous code example:
2564 ```compile_fail,E0325
2573 // error: item `N` is an associated type, which doesn't match its
2574 // trait `<Bar as Foo>`
2578 Please verify that the associated type name wasn't misspelled and your
2579 implementation corresponds to the trait definition. Example:
2589 type N = u32; // ok!
2603 const N : u32 = 0; // ok!
2609 The types of any associated constants in a trait implementation must match the
2610 types in the trait definition. This error indicates that there was a mismatch.
2612 Here's an example of this error:
2614 ```compile_fail,E0326
2622 const BAR: u32 = 5; // error, expected bool, found u32
2628 The Unsize trait should not be implemented directly. All implementations of
2629 Unsize are provided automatically by the compiler.
2631 Erroneous code example:
2633 ```compile_fail,E0328
2636 use std::marker::Unsize;
2640 impl<T> Unsize<T> for MyType {}
2643 If you are defining your own smart pointer type and would like to enable
2644 conversion from a sized to an unsized type with the
2645 [DST coercion system][RFC 982], use [`CoerceUnsized`] instead.
2648 #![feature(coerce_unsized)]
2650 use std::ops::CoerceUnsized;
2652 pub struct MyType<T: ?Sized> {
2653 field_with_unsized_type: T,
2656 impl<T, U> CoerceUnsized<MyType<U>> for MyType<T>
2657 where T: CoerceUnsized<U> {}
2660 [RFC 982]: https://github.com/rust-lang/rfcs/blob/master/text/0982-dst-coercion.md
2661 [`CoerceUnsized`]: https://doc.rust-lang.org/std/ops/trait.CoerceUnsized.html
2665 // Associated consts can now be accessed through generic type parameters, and
2666 // this error is no longer emitted.
2668 // FIXME: consider whether to leave it in the error index, or remove it entirely
2669 // as associated consts is not stabilized yet.
2672 An attempt was made to access an associated constant through either a generic
2673 type parameter or `Self`. This is not supported yet. An example causing this
2674 error is shown below:
2683 impl Foo for MyStruct {
2684 const BAR: f64 = 0f64;
2687 fn get_bar_bad<F: Foo>(t: F) -> f64 {
2692 Currently, the value of `BAR` for a particular type can only be accessed
2693 through a concrete type, as shown below:
2702 fn get_bar_good() -> f64 {
2703 <MyStruct as Foo>::BAR
2710 An attempt was made to implement `Drop` on a concrete specialization of a
2711 generic type. An example is shown below:
2713 ```compile_fail,E0366
2718 impl Drop for Foo<u32> {
2719 fn drop(&mut self) {}
2723 This code is not legal: it is not possible to specialize `Drop` to a subset of
2724 implementations of a generic type. One workaround for this is to wrap the
2725 generic type, as shown below:
2737 fn drop(&mut self) {}
2743 An attempt was made to implement `Drop` on a specialization of a generic type.
2744 An example is shown below:
2746 ```compile_fail,E0367
2749 struct MyStruct<T> {
2753 impl<T: Foo> Drop for MyStruct<T> {
2754 fn drop(&mut self) {}
2758 This code is not legal: it is not possible to specialize `Drop` to a subset of
2759 implementations of a generic type. In order for this code to work, `MyStruct`
2760 must also require that `T` implements `Foo`. Alternatively, another option is
2761 to wrap the generic type in another that specializes appropriately:
2766 struct MyStruct<T> {
2770 struct MyStructWrapper<T: Foo> {
2774 impl <T: Foo> Drop for MyStructWrapper<T> {
2775 fn drop(&mut self) {}
2781 This error indicates that a binary assignment operator like `+=` or `^=` was
2782 applied to a type that doesn't support it. For example:
2784 ```compile_fail,E0368
2785 let mut x = 12f32; // error: binary operation `<<` cannot be applied to
2791 To fix this error, please check that this type implements this binary
2795 let mut x = 12u32; // the `u32` type does implement the `ShlAssign` trait
2800 It is also possible to overload most operators for your own type by
2801 implementing the `[OP]Assign` traits from `std::ops`.
2803 Another problem you might be facing is this: suppose you've overloaded the `+`
2804 operator for some type `Foo` by implementing the `std::ops::Add` trait for
2805 `Foo`, but you find that using `+=` does not work, as in this example:
2807 ```compile_fail,E0368
2815 fn add(self, rhs: Foo) -> Foo {
2821 let mut x: Foo = Foo(5);
2822 x += Foo(7); // error, `+= cannot be applied to the type `Foo`
2826 This is because `AddAssign` is not automatically implemented, so you need to
2827 manually implement it for your type.
2831 A binary operation was attempted on a type which doesn't support it.
2832 Erroneous code example:
2834 ```compile_fail,E0369
2835 let x = 12f32; // error: binary operation `<<` cannot be applied to
2841 To fix this error, please check that this type implements this binary
2845 let x = 12u32; // the `u32` type does implement it:
2846 // https://doc.rust-lang.org/stable/std/ops/trait.Shl.html
2851 It is also possible to overload most operators for your own type by
2852 implementing traits from `std::ops`.
2854 String concatenation appends the string on the right to the string on the
2855 left and may require reallocation. This requires ownership of the string
2856 on the left. If something should be added to a string literal, move the
2857 literal to the heap by allocating it with `to_owned()` like in
2858 `"Your text".to_owned()`.
2863 The maximum value of an enum was reached, so it cannot be automatically
2864 set in the next enum value. Erroneous code example:
2866 ```compile_fail,E0370
2869 X = 0x7fffffffffffffff,
2870 Y, // error: enum discriminant overflowed on value after
2871 // 9223372036854775807: i64; set explicitly via
2872 // Y = -9223372036854775808 if that is desired outcome
2876 To fix this, please set manually the next enum value or put the enum variant
2877 with the maximum value at the end of the enum. Examples:
2882 X = 0x7fffffffffffffff,
2893 X = 0x7fffffffffffffff,
2899 When `Trait2` is a subtrait of `Trait1` (for example, when `Trait2` has a
2900 definition like `trait Trait2: Trait1 { ... }`), it is not allowed to implement
2901 `Trait1` for `Trait2`. This is because `Trait2` already implements `Trait1` by
2902 definition, so it is not useful to do this.
2906 ```compile_fail,E0371
2907 trait Foo { fn foo(&self) { } }
2911 impl Bar for Baz { } // error, `Baz` implements `Bar` by definition
2912 impl Foo for Baz { } // error, `Baz` implements `Bar` which implements `Foo`
2913 impl Baz for Baz { } // error, `Baz` (trivially) implements `Baz`
2914 impl Baz for Bar { } // Note: This is OK
2919 A struct without a field containing an unsized type cannot implement
2920 `CoerceUnsized`. An [unsized type][1] is any type that the compiler
2921 doesn't know the length or alignment of at compile time. Any struct
2922 containing an unsized type is also unsized.
2924 [1]: https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait
2926 Example of erroneous code:
2928 ```compile_fail,E0374
2929 #![feature(coerce_unsized)]
2930 use std::ops::CoerceUnsized;
2932 struct Foo<T: ?Sized> {
2936 // error: Struct `Foo` has no unsized fields that need `CoerceUnsized`.
2937 impl<T, U> CoerceUnsized<Foo<U>> for Foo<T>
2938 where T: CoerceUnsized<U> {}
2941 `CoerceUnsized` is used to coerce one struct containing an unsized type
2942 into another struct containing a different unsized type. If the struct
2943 doesn't have any fields of unsized types then you don't need explicit
2944 coercion to get the types you want. To fix this you can either
2945 not try to implement `CoerceUnsized` or you can add a field that is
2946 unsized to the struct.
2951 #![feature(coerce_unsized)]
2952 use std::ops::CoerceUnsized;
2954 // We don't need to impl `CoerceUnsized` here.
2959 // We add the unsized type field to the struct.
2960 struct Bar<T: ?Sized> {
2965 // The struct has an unsized field so we can implement
2966 // `CoerceUnsized` for it.
2967 impl<T, U> CoerceUnsized<Bar<U>> for Bar<T>
2968 where T: CoerceUnsized<U> {}
2971 Note that `CoerceUnsized` is mainly used by smart pointers like `Box`, `Rc`
2972 and `Arc` to be able to mark that they can coerce unsized types that they
2977 A struct with more than one field containing an unsized type cannot implement
2978 `CoerceUnsized`. This only occurs when you are trying to coerce one of the
2979 types in your struct to another type in the struct. In this case we try to
2980 impl `CoerceUnsized` from `T` to `U` which are both types that the struct
2981 takes. An [unsized type][1] is any type that the compiler doesn't know the
2982 length or alignment of at compile time. Any struct containing an unsized type
2985 Example of erroneous code:
2987 ```compile_fail,E0375
2988 #![feature(coerce_unsized)]
2989 use std::ops::CoerceUnsized;
2991 struct Foo<T: ?Sized, U: ?Sized> {
2997 // error: Struct `Foo` has more than one unsized field.
2998 impl<T, U> CoerceUnsized<Foo<U, T>> for Foo<T, U> {}
3001 `CoerceUnsized` only allows for coercion from a structure with a single
3002 unsized type field to another struct with a single unsized type field.
3003 In fact Rust only allows for a struct to have one unsized type in a struct
3004 and that unsized type must be the last field in the struct. So having two
3005 unsized types in a single struct is not allowed by the compiler. To fix this
3006 use only one field containing an unsized type in the struct and then use
3007 multiple structs to manage each unsized type field you need.
3012 #![feature(coerce_unsized)]
3013 use std::ops::CoerceUnsized;
3015 struct Foo<T: ?Sized> {
3020 impl <T, U> CoerceUnsized<Foo<U>> for Foo<T>
3021 where T: CoerceUnsized<U> {}
3023 fn coerce_foo<T: CoerceUnsized<U>, U>(t: T) -> Foo<U> {
3024 Foo { a: 12i32, b: t } // we use coercion to get the `Foo<U>` type we need
3028 [1]: https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait
3032 The type you are trying to impl `CoerceUnsized` for is not a struct.
3033 `CoerceUnsized` can only be implemented for a struct. Unsized types are
3034 already able to be coerced without an implementation of `CoerceUnsized`
3035 whereas a struct containing an unsized type needs to know the unsized type
3036 field it's containing is able to be coerced. An [unsized type][1]
3037 is any type that the compiler doesn't know the length or alignment of at
3038 compile time. Any struct containing an unsized type is also unsized.
3040 [1]: https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait
3042 Example of erroneous code:
3044 ```compile_fail,E0376
3045 #![feature(coerce_unsized)]
3046 use std::ops::CoerceUnsized;
3048 struct Foo<T: ?Sized> {
3052 // error: The type `U` is not a struct
3053 impl<T, U> CoerceUnsized<U> for Foo<T> {}
3056 The `CoerceUnsized` trait takes a struct type. Make sure the type you are
3057 providing to `CoerceUnsized` is a struct with only the last field containing an
3063 #![feature(coerce_unsized)]
3064 use std::ops::CoerceUnsized;
3070 // The `Foo<U>` is a struct so `CoerceUnsized` can be implemented
3071 impl<T, U> CoerceUnsized<Foo<U>> for Foo<T> where T: CoerceUnsized<U> {}
3074 Note that in Rust, structs can only contain an unsized type if the field
3075 containing the unsized type is the last and only unsized type field in the
3080 The `DispatchFromDyn` trait currently can only be implemented for
3081 builtin pointer types and structs that are newtype wrappers around them
3082 — that is, the struct must have only one field (except for`PhantomData`),
3083 and that field must itself implement `DispatchFromDyn`.
3088 #![feature(dispatch_from_dyn, unsize)]
3091 ops::DispatchFromDyn,
3094 struct Ptr<T: ?Sized>(*const T);
3096 impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Ptr<U>> for Ptr<T>
3103 #![feature(dispatch_from_dyn)]
3105 ops::DispatchFromDyn,
3106 marker::PhantomData,
3111 _phantom: PhantomData<()>,
3114 impl<T, U> DispatchFromDyn<Wrapper<U>> for Wrapper<T>
3116 T: DispatchFromDyn<U>,
3120 Example of illegal `DispatchFromDyn` implementation
3121 (illegal because of extra field)
3123 ```compile-fail,E0378
3124 #![feature(dispatch_from_dyn)]
3125 use std::ops::DispatchFromDyn;
3127 struct WrapperExtraField<T> {
3132 impl<T, U> DispatchFromDyn<WrapperExtraField<U>> for WrapperExtraField<T>
3134 T: DispatchFromDyn<U>,
3140 You tried to implement methods for a primitive type. Erroneous code example:
3142 ```compile_fail,E0390
3148 // error: only a single inherent implementation marked with
3149 // `#[lang = "mut_ptr"]` is allowed for the `*mut T` primitive
3152 This isn't allowed, but using a trait to implement a method is a good solution.
3164 impl Bar for *mut Foo {
3171 This error indicates that a type or lifetime parameter has been declared
3172 but not actually used. Here is an example that demonstrates the error:
3174 ```compile_fail,E0392
3180 If the type parameter was included by mistake, this error can be fixed
3181 by simply removing the type parameter, as shown below:
3189 Alternatively, if the type parameter was intentionally inserted, it must be
3190 used. A simple fix is shown below:
3198 This error may also commonly be found when working with unsafe code. For
3199 example, when using raw pointers one may wish to specify the lifetime for
3200 which the pointed-at data is valid. An initial attempt (below) causes this
3203 ```compile_fail,E0392
3209 We want to express the constraint that Foo should not outlive `'a`, because
3210 the data pointed to by `T` is only valid for that lifetime. The problem is
3211 that there are no actual uses of `'a`. It's possible to work around this
3212 by adding a PhantomData type to the struct, using it to tell the compiler
3213 to act as if the struct contained a borrowed reference `&'a T`:
3216 use std::marker::PhantomData;
3218 struct Foo<'a, T: 'a> {
3220 phantom: PhantomData<&'a T>
3224 [PhantomData] can also be used to express information about unused type
3227 [PhantomData]: https://doc.rust-lang.org/std/marker/struct.PhantomData.html
3231 A type parameter which references `Self` in its default value was not specified.
3232 Example of erroneous code:
3234 ```compile_fail,E0393
3237 fn together_we_will_rule_the_galaxy(son: &A) {}
3238 // error: the type parameter `T` must be explicitly specified in an
3239 // object type because its default value `Self` references the
3243 A trait object is defined over a single, fully-defined trait. With a regular
3244 default parameter, this parameter can just be substituted in. However, if the
3245 default parameter is `Self`, the trait changes for each concrete type; i.e.
3246 `i32` will be expected to implement `A<i32>`, `bool` will be expected to
3247 implement `A<bool>`, etc... These types will not share an implementation of a
3248 fully-defined trait; instead they share implementations of a trait with
3249 different parameters substituted in for each implementation. This is
3250 irreconcilable with what we need to make a trait object work, and is thus
3251 disallowed. Making the trait concrete by explicitly specifying the value of the
3252 defaulted parameter will fix this issue. Fixed example:
3257 fn together_we_will_rule_the_galaxy(son: &A<i32>) {} // Ok!
3262 You implemented a trait, overriding one or more of its associated types but did
3263 not reimplement its default methods.
3265 Example of erroneous code:
3267 ```compile_fail,E0399
3268 #![feature(associated_type_defaults)]
3276 // error - the following trait items need to be reimplemented as
3277 // `Assoc` was overridden: `bar`
3282 To fix this, add an implementation for each default method from the trait:
3285 #![feature(associated_type_defaults)]
3294 fn bar(&self) {} // ok!
3300 The functional record update syntax is only allowed for structs. (Struct-like
3301 enum variants don't qualify, for example.)
3303 Erroneous code example:
3305 ```compile_fail,E0436
3306 enum PublicationFrequency {
3308 SemiMonthly { days: (u8, u8), annual_special: bool },
3311 fn one_up_competitor(competitor_frequency: PublicationFrequency)
3312 -> PublicationFrequency {
3313 match competitor_frequency {
3314 PublicationFrequency::Weekly => PublicationFrequency::SemiMonthly {
3315 days: (1, 15), annual_special: false
3317 c @ PublicationFrequency::SemiMonthly{ .. } =>
3318 PublicationFrequency::SemiMonthly {
3319 annual_special: true, ..c // error: functional record update
3320 // syntax requires a struct
3326 Rewrite the expression without functional record update syntax:
3329 enum PublicationFrequency {
3331 SemiMonthly { days: (u8, u8), annual_special: bool },
3334 fn one_up_competitor(competitor_frequency: PublicationFrequency)
3335 -> PublicationFrequency {
3336 match competitor_frequency {
3337 PublicationFrequency::Weekly => PublicationFrequency::SemiMonthly {
3338 days: (1, 15), annual_special: false
3340 PublicationFrequency::SemiMonthly{ days, .. } =>
3341 PublicationFrequency::SemiMonthly {
3342 days, annual_special: true // ok!
3350 The length of the platform-intrinsic function `simd_shuffle`
3351 wasn't specified. Erroneous code example:
3353 ```compile_fail,E0439
3354 #![feature(platform_intrinsics)]
3356 extern "platform-intrinsic" {
3357 fn simd_shuffle<A,B>(a: A, b: A, c: [u32; 8]) -> B;
3358 // error: invalid `simd_shuffle`, needs length: `simd_shuffle`
3362 The `simd_shuffle` function needs the length of the array passed as
3363 last parameter in its name. Example:
3366 #![feature(platform_intrinsics)]
3368 extern "platform-intrinsic" {
3369 fn simd_shuffle8<A,B>(a: A, b: A, c: [u32; 8]) -> B;
3375 The `typeof` keyword is currently reserved but unimplemented.
3376 Erroneous code example:
3378 ```compile_fail,E0516
3380 let x: typeof(92) = 92;
3384 Try using type inference instead. Example:
3394 A non-default implementation was already made on this type so it cannot be
3395 specialized further. Erroneous code example:
3397 ```compile_fail,E0520
3398 #![feature(specialization)]
3405 impl<T> SpaceLlama for T {
3406 default fn fly(&self) {}
3410 // applies to all `Clone` T and overrides the previous impl
3411 impl<T: Clone> SpaceLlama for T {
3415 // since `i32` is clone, this conflicts with the previous implementation
3416 impl SpaceLlama for i32 {
3417 default fn fly(&self) {}
3418 // error: item `fly` is provided by an `impl` that specializes
3419 // another, but the item in the parent `impl` is not marked
3420 // `default` and so it cannot be specialized.
3424 Specialization only allows you to override `default` functions in
3427 To fix this error, you need to mark all the parent implementations as default.
3431 #![feature(specialization)]
3438 impl<T> SpaceLlama for T {
3439 default fn fly(&self) {} // This is a parent implementation.
3442 // applies to all `Clone` T; overrides the previous impl
3443 impl<T: Clone> SpaceLlama for T {
3444 default fn fly(&self) {} // This is a parent implementation but was
3445 // previously not a default one, causing the error
3448 // applies to i32, overrides the previous two impls
3449 impl SpaceLlama for i32 {
3450 fn fly(&self) {} // And now that's ok!
3456 The number of elements in an array or slice pattern differed from the number of
3457 elements in the array being matched.
3459 Example of erroneous code:
3461 ```compile_fail,E0527
3462 let r = &[1, 2, 3, 4];
3464 &[a, b] => { // error: pattern requires 2 elements but array
3466 println!("a={}, b={}", a, b);
3471 Ensure that the pattern is consistent with the size of the matched
3472 array. Additional elements can be matched with `..`:
3475 #![feature(slice_patterns)]
3477 let r = &[1, 2, 3, 4];
3479 &[a, b, ..] => { // ok!
3480 println!("a={}, b={}", a, b);
3487 An array or slice pattern required more elements than were present in the
3490 Example of erroneous code:
3492 ```compile_fail,E0528
3493 #![feature(slice_patterns)]
3497 &[a, b, c, rest..] => { // error: pattern requires at least 3
3498 // elements but array has 2
3499 println!("a={}, b={}, c={} rest={:?}", a, b, c, rest);
3504 Ensure that the matched array has at least as many elements as the pattern
3505 requires. You can match an arbitrary number of remaining elements with `..`:
3508 #![feature(slice_patterns)]
3510 let r = &[1, 2, 3, 4, 5];
3512 &[a, b, c, rest..] => { // ok!
3513 // prints `a=1, b=2, c=3 rest=[4, 5]`
3514 println!("a={}, b={}, c={} rest={:?}", a, b, c, rest);
3521 An array or slice pattern was matched against some other type.
3523 Example of erroneous code:
3525 ```compile_fail,E0529
3528 [a, b] => { // error: expected an array or slice, found `f32`
3529 println!("a={}, b={}", a, b);
3534 Ensure that the pattern and the expression being matched on are of consistent
3541 println!("a={}, b={}", a, b);
3548 The `inline` attribute was malformed.
3550 Erroneous code example:
3552 ```ignore (compile_fail not working here; see Issue #43707)
3553 #[inline()] // error: expected one argument
3554 pub fn something() {}
3559 The parenthesized `inline` attribute requires the parameter to be specified:
3573 Alternatively, a paren-less version of the attribute may be used to hint the
3574 compiler about inlining opportunity:
3581 For more information about the inline attribute, read:
3582 https://doc.rust-lang.org/reference.html#inline-attributes
3586 An unknown argument was given to the `inline` attribute.
3588 Erroneous code example:
3590 ```ignore (compile_fail not working here; see Issue #43707)
3591 #[inline(unknown)] // error: invalid argument
3592 pub fn something() {}
3597 The `inline` attribute only supports two arguments:
3602 All other arguments given to the `inline` attribute will return this error.
3606 #[inline(never)] // ok!
3607 pub fn something() {}
3612 For more information about the inline attribute, https:
3613 read://doc.rust-lang.org/reference.html#inline-attributes
3617 An unknown field was specified into an enum's structure variant.
3619 Erroneous code example:
3621 ```compile_fail,E0559
3626 let s = Field::Fool { joke: 0 };
3627 // error: struct variant `Field::Fool` has no field named `joke`
3630 Verify you didn't misspell the field's name or that the field exists. Example:
3637 let s = Field::Fool { joke: 0 }; // ok!
3642 An unknown field was specified into a structure.
3644 Erroneous code example:
3646 ```compile_fail,E0560
3651 let s = Simba { mother: 1, father: 0 };
3652 // error: structure `Simba` has no field named `father`
3655 Verify you didn't misspell the field's name or that the field exists. Example:
3663 let s = Simba { mother: 1, father: 0 }; // ok!
3668 If an impl has a generic parameter with the `#[may_dangle]` attribute, then
3669 that impl must be declared as an `unsafe impl.
3671 Erroneous code example:
3673 ```compile_fail,E0569
3674 #![feature(dropck_eyepatch)]
3677 impl<#[may_dangle] X> Drop for Foo<X> {
3678 fn drop(&mut self) { }
3682 In this example, we are asserting that the destructor for `Foo` will not
3683 access any data of type `X`, and require this assertion to be true for
3684 overall safety in our program. The compiler does not currently attempt to
3685 verify this assertion; therefore we must tag this `impl` as unsafe.
3689 The requested ABI is unsupported by the current target.
3691 The rust compiler maintains for each target a blacklist of ABIs unsupported on
3692 that target. If an ABI is present in such a list this usually means that the
3693 target / ABI combination is currently unsupported by llvm.
3695 If necessary, you can circumvent this check using custom target specifications.
3699 A return statement was found outside of a function body.
3701 Erroneous code example:
3703 ```compile_fail,E0572
3704 const FOO: u32 = return 0; // error: return statement outside of function body
3709 To fix this issue, just remove the return keyword or move the expression into a
3715 fn some_fn() -> u32 {
3726 In a `fn` type, a lifetime appears only in the return type,
3727 and not in the arguments types.
3729 Erroneous code example:
3731 ```compile_fail,E0581
3733 // Here, `'a` appears only in the return type:
3734 let x: for<'a> fn() -> &'a i32;
3738 To fix this issue, either use the lifetime in the arguments, or use
3743 // Here, `'a` appears only in the return type:
3744 let x: for<'a> fn(&'a i32) -> &'a i32;
3745 let y: fn() -> &'static i32;
3749 Note: The examples above used to be (erroneously) accepted by the
3750 compiler, but this was since corrected. See [issue #33685] for more
3753 [issue #33685]: https://github.com/rust-lang/rust/issues/33685
3757 A lifetime appears only in an associated-type binding,
3758 and not in the input types to the trait.
3760 Erroneous code example:
3762 ```compile_fail,E0582
3764 // No type can satisfy this requirement, since `'a` does not
3765 // appear in any of the input types (here, `i32`):
3766 where F: for<'a> Fn(i32) -> Option<&'a i32>
3773 To fix this issue, either use the lifetime in the inputs, or use
3777 fn bar<F, G>(t: F, u: G)
3778 where F: for<'a> Fn(&'a i32) -> Option<&'a i32>,
3779 G: Fn(i32) -> Option<&'static i32>,
3786 Note: The examples above used to be (erroneously) accepted by the
3787 compiler, but this was since corrected. See [issue #33685] for more
3790 [issue #33685]: https://github.com/rust-lang/rust/issues/33685
3794 This error occurs when a method is used on a type which doesn't implement it:
3796 Erroneous code example:
3798 ```compile_fail,E0599
3802 x.chocolate(); // error: no method named `chocolate` found for type `Mouth`
3803 // in the current scope
3808 An unary operator was used on a type which doesn't implement it.
3810 Example of erroneous code:
3812 ```compile_fail,E0600
3818 !Question::Yes; // error: cannot apply unary operator `!` to type `Question`
3821 In this case, `Question` would need to implement the `std::ops::Not` trait in
3822 order to be able to use `!` on it. Let's implement it:
3832 // We implement the `Not` trait on the enum.
3833 impl Not for Question {
3836 fn not(self) -> bool {
3838 Question::Yes => false, // If the `Answer` is `Yes`, then it
3840 Question::No => true, // And here we do the opposite.
3845 assert_eq!(!Question::Yes, false);
3846 assert_eq!(!Question::No, true);
3851 An attempt to index into a type which doesn't implement the `std::ops::Index`
3852 trait was performed.
3854 Erroneous code example:
3856 ```compile_fail,E0608
3857 0u8[2]; // error: cannot index into a value of type `u8`
3860 To be able to index into a type it needs to implement the `std::ops::Index`
3864 let v: Vec<u8> = vec![0, 1, 2, 3];
3866 // The `Vec` type implements the `Index` trait so you can do:
3867 println!("{}", v[2]);
3872 A cast to `char` was attempted on a type other than `u8`.
3874 Erroneous code example:
3876 ```compile_fail,E0604
3877 0u32 as char; // error: only `u8` can be cast as `char`, not `u32`
3880 As the error message indicates, only `u8` can be cast into `char`. Example:
3883 let c = 86u8 as char; // ok!
3887 For more information about casts, take a look at the Type cast section in
3888 [The Reference Book][1].
3890 [1]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
3894 An invalid cast was attempted.
3896 Erroneous code examples:
3898 ```compile_fail,E0605
3900 x as Vec<u8>; // error: non-primitive cast: `u8` as `std::vec::Vec<u8>`
3904 let v = 0 as *const u8; // So here, `v` is a `*const u8`.
3905 v as &u8; // error: non-primitive cast: `*const u8` as `&u8`
3908 Only primitive types can be cast into each other. Examples:
3914 let v = 0 as *const u8;
3915 v as *const i8; // ok!
3918 For more information about casts, take a look at the Type cast section in
3919 [The Reference Book][1].
3921 [1]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
3925 An incompatible cast was attempted.
3927 Erroneous code example:
3929 ```compile_fail,E0606
3930 let x = &0u8; // Here, `x` is a `&u8`.
3931 let y: u32 = x as u32; // error: casting `&u8` as `u32` is invalid
3934 When casting, keep in mind that only primitive types can be cast into each
3939 let y: u32 = *x as u32; // We dereference it first and then cast it.
3942 For more information about casts, take a look at the Type cast section in
3943 [The Reference Book][1].
3945 [1]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
3949 A cast between a thin and a fat pointer was attempted.
3951 Erroneous code example:
3953 ```compile_fail,E0607
3954 let v = 0 as *const u8;
3958 First: what are thin and fat pointers?
3960 Thin pointers are "simple" pointers: they are purely a reference to a memory
3963 Fat pointers are pointers referencing Dynamically Sized Types (also called DST).
3964 DST don't have a statically known size, therefore they can only exist behind
3965 some kind of pointers that contain additional information. Slices and trait
3966 objects are DSTs. In the case of slices, the additional information the fat
3967 pointer holds is their size.
3969 To fix this error, don't try to cast directly between thin and fat pointers.
3971 For more information about casts, take a look at the Type cast section in
3972 [The Reference Book][1].
3974 [1]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
3978 Attempted to access a non-existent field in a struct.
3980 Erroneous code example:
3982 ```compile_fail,E0609
3983 struct StructWithFields {
3987 let s = StructWithFields { x: 0 };
3988 println!("{}", s.foo); // error: no field `foo` on type `StructWithFields`
3991 To fix this error, check that you didn't misspell the field's name or that the
3992 field actually exists. Example:
3995 struct StructWithFields {
3999 let s = StructWithFields { x: 0 };
4000 println!("{}", s.x); // ok!
4005 Attempted to access a field on a primitive type.
4007 Erroneous code example:
4009 ```compile_fail,E0610
4011 println!("{}", x.foo); // error: `{integer}` is a primitive type, therefore
4012 // doesn't have fields
4015 Primitive types are the most basic types available in Rust and don't have
4016 fields. To access data via named fields, struct types are used. Example:
4019 // We declare struct called `Foo` containing two fields:
4025 // We create an instance of this struct:
4026 let variable = Foo { x: 0, y: -12 };
4027 // And we can now access its fields:
4028 println!("x: {}, y: {}", variable.x, variable.y);
4031 For more information about primitives and structs, take a look at The Book:
4032 https://doc.rust-lang.org/book/ch03-02-data-types.html
4033 https://doc.rust-lang.org/book/ch05-00-structs.html
4037 Attempted to dereference a variable which cannot be dereferenced.
4039 Erroneous code example:
4041 ```compile_fail,E0614
4043 *y; // error: type `u32` cannot be dereferenced
4046 Only types implementing `std::ops::Deref` can be dereferenced (such as `&T`).
4052 // So here, `x` is a `&u32`, so we can dereference it:
4058 Attempted to access a method like a field.
4060 Erroneous code example:
4062 ```compile_fail,E0615
4071 let f = Foo { x: 0 };
4072 f.method; // error: attempted to take value of method `method` on type `Foo`
4075 If you want to use a method, add `()` after it:
4078 # struct Foo { x: u32 }
4079 # impl Foo { fn method(&self) {} }
4080 # let f = Foo { x: 0 };
4084 However, if you wanted to access a field of a struct check that the field name
4085 is spelled correctly. Example:
4088 # struct Foo { x: u32 }
4089 # impl Foo { fn method(&self) {} }
4090 # let f = Foo { x: 0 };
4091 println!("{}", f.x);
4096 Attempted to access a private field on a struct.
4098 Erroneous code example:
4100 ```compile_fail,E0616
4103 x: u32, // So `x` is private in here.
4107 pub fn new() -> Foo { Foo { x: 0 } }
4111 let f = some_module::Foo::new();
4112 println!("{}", f.x); // error: field `x` of struct `some_module::Foo` is private
4115 If you want to access this field, you have two options:
4117 1) Set the field public:
4122 pub x: u32, // `x` is now public.
4126 pub fn new() -> Foo { Foo { x: 0 } }
4130 let f = some_module::Foo::new();
4131 println!("{}", f.x); // ok!
4134 2) Add a getter function:
4139 x: u32, // So `x` is still private in here.
4143 pub fn new() -> Foo { Foo { x: 0 } }
4145 // We create the getter function here:
4146 pub fn get_x(&self) -> &u32 { &self.x }
4150 let f = some_module::Foo::new();
4151 println!("{}", f.get_x()); // ok!
4156 Attempted to pass an invalid type of variable into a variadic function.
4158 Erroneous code example:
4160 ```compile_fail,E0617
4162 fn printf(c: *const i8, ...);
4166 printf(::std::ptr::null(), 0f32);
4167 // error: can't pass an `f32` to variadic function, cast to `c_double`
4171 Certain Rust types must be cast before passing them to a variadic function,
4172 because of arcane ABI rules dictated by the C standard. To fix the error,
4173 cast the value to the type specified by the error message (which you may need
4174 to import from `std::os::raw`).
4178 Attempted to call something which isn't a function nor a method.
4180 Erroneous code examples:
4182 ```compile_fail,E0618
4187 X::Entry(); // error: expected function, found `X::Entry`
4191 x(); // error: expected function, found `i32`
4194 Only functions and methods can be called using `()`. Example:
4197 // We declare a function:
4198 fn i_am_a_function() {}
4206 #### Note: this error code is no longer emitted by the compiler.
4207 The type-checker needed to know the type of an expression, but that type had not
4210 Erroneous code example:
4216 // Here, the type of `v` is not (yet) known, so we
4217 // cannot resolve this method call:
4218 v.to_uppercase(); // error: the type of this value must be known in
4225 Type inference typically proceeds from the top of the function to the bottom,
4226 figuring out types as it goes. In some cases -- notably method calls and
4227 overloadable operators like `*` -- the type checker may not have enough
4228 information *yet* to make progress. This can be true even if the rest of the
4229 function provides enough context (because the type-checker hasn't looked that
4230 far ahead yet). In this case, type annotations can be used to help it along.
4232 To fix this error, just specify the type of the variable. Example:
4235 let mut x: Vec<String> = vec![]; // We precise the type of the vec elements.
4238 v.to_uppercase(); // Since rustc now knows the type of the vec elements,
4239 // we can use `v`'s methods.
4247 A cast to an unsized type was attempted.
4249 Erroneous code example:
4251 ```compile_fail,E0620
4252 let x = &[1_usize, 2] as [usize]; // error: cast to unsized type: `&[usize; 2]`
4256 In Rust, some types don't have a known size at compile-time. For example, in a
4257 slice type like `[u32]`, the number of elements is not known at compile-time and
4258 hence the overall size cannot be computed. As a result, such types can only be
4259 manipulated through a reference (e.g., `&T` or `&mut T`) or other pointer-type
4260 (e.g., `Box` or `Rc`). Try casting to a reference instead:
4263 let x = &[1_usize, 2] as &[usize]; // ok!
4268 An intrinsic was declared without being a function.
4270 Erroneous code example:
4272 ```compile_fail,E0622
4273 #![feature(intrinsics)]
4274 extern "rust-intrinsic" {
4275 pub static breakpoint : unsafe extern "rust-intrinsic" fn();
4276 // error: intrinsic must be a function
4279 fn main() { unsafe { breakpoint(); } }
4282 An intrinsic is a function available for use in a given programming language
4283 whose implementation is handled specially by the compiler. In order to fix this
4284 error, just declare a function.
4288 A private item was used outside of its scope.
4290 Erroneous code example:
4292 ```compile_fail,E0624
4301 let foo = inner::Foo;
4302 foo.method(); // error: method `method` is private
4305 Two possibilities are available to solve this issue:
4307 1. Only use the item in the scope it has been defined:
4317 pub fn call_method(foo: &Foo) { // We create a public function.
4318 foo.method(); // Which calls the item.
4322 let foo = inner::Foo;
4323 inner::call_method(&foo); // And since the function is public, we can call the
4324 // method through it.
4327 2. Make the item public:
4334 pub fn method(&self) {} // It's now public.
4338 let foo = inner::Foo;
4339 foo.method(); // Ok!
4344 This error indicates that the struct, enum or enum variant must be matched
4345 non-exhaustively as it has been marked as `non_exhaustive`.
4347 When applied within a crate, downstream users of the crate will need to use the
4348 `_` pattern when matching enums and use the `..` pattern when matching structs.
4349 Downstream crates cannot match against non-exhaustive enum variants.
4351 For example, in the below example, since the enum is marked as
4352 `non_exhaustive`, it is required that downstream crates match non-exhaustively
4355 ```rust,ignore (pseudo-Rust)
4356 use std::error::Error as StdError;
4358 #[non_exhaustive] pub enum Error {
4363 impl StdError for Error {
4364 fn description(&self) -> &str {
4365 // This will not error, despite being marked as non_exhaustive, as this
4366 // enum is defined within the current crate, it can be matched
4369 Message(ref s) => s,
4370 Other => "other or unknown error",
4376 An example of matching non-exhaustively on the above enum is provided below:
4378 ```rust,ignore (pseudo-Rust)
4381 // This will not error as the non_exhaustive Error enum has been matched with a
4384 Message(ref s) => ...,
4390 Similarly, for structs, match with `..` to avoid this error.
4394 This error indicates that the struct, enum or enum variant cannot be
4395 instantiated from outside of the defining crate as it has been marked
4396 as `non_exhaustive` and as such more fields/variants may be added in
4397 future that could cause adverse side effects for this code.
4399 It is recommended that you look for a `new` function or equivalent in the
4400 crate's documentation.
4404 This error indicates that there is a mismatch between generic parameters and
4405 impl Trait parameters in a trait declaration versus its impl.
4407 ```compile_fail,E0643
4409 fn foo(&self, _: &impl Iterator);
4412 fn foo<U: Iterator>(&self, _: &U) { } // error method `foo` has incompatible
4413 // signature for trait
4419 It is not possible to define `main` with a where clause.
4420 Erroneous code example:
4422 ```compile_fail,E0646
4423 fn main() where i32: Copy { // error: main function is not allowed to have
4430 It is not possible to define `start` with a where clause.
4431 Erroneous code example:
4433 ```compile_fail,E0647
4437 fn start(_: isize, _: *const *const u8) -> isize where (): Copy {
4438 //^ error: start function is not allowed to have a where clause
4445 `export_name` attributes may not contain null characters (`\0`).
4447 ```compile_fail,E0648
4448 #[export_name="\0foo"] // error: `export_name` may not contain null characters
4454 This error indicates that the numeric value for the method being passed exists
4455 but the type of the numeric value or binding could not be identified.
4457 The error happens on numeric literals:
4459 ```compile_fail,E0689
4463 and on numeric bindings without an identified concrete type:
4465 ```compile_fail,E0689
4467 x.neg(); // same error as above
4470 Because of this, you must give the numeric literal or binding a type:
4475 let _ = 2.0_f32.neg();
4478 let _ = (2.0 as f32).neg();
4483 A struct with the representation hint `repr(transparent)` had zero or more than
4484 on fields that were not guaranteed to be zero-sized.
4486 Erroneous code example:
4488 ```compile_fail,E0690
4489 #[repr(transparent)]
4490 struct LengthWithUnit<U> { // error: transparent struct needs exactly one
4491 value: f32, // non-zero-sized field, but has 2
4496 Because transparent structs are represented exactly like one of their fields at
4497 run time, said field must be uniquely determined. If there is no field, or if
4498 there are multiple fields, it is not clear how the struct should be represented.
4499 Note that fields of zero-typed types (e.g., `PhantomData`) can also exist
4500 alongside the field that contains the actual data, they do not count for this
4501 error. When generic types are involved (as in the above example), an error is
4502 reported because the type parameter could be non-zero-sized.
4504 To combine `repr(transparent)` with type parameters, `PhantomData` may be
4508 use std::marker::PhantomData;
4510 #[repr(transparent)]
4511 struct LengthWithUnit<U> {
4513 unit: PhantomData<U>,
4519 A struct with the `repr(transparent)` representation hint contains a zero-sized
4520 field that requires non-trivial alignment.
4522 Erroneous code example:
4524 ```compile_fail,E0691
4525 #![feature(repr_align)]
4528 struct ForceAlign32;
4530 #[repr(transparent)]
4531 struct Wrapper(f32, ForceAlign32); // error: zero-sized field in transparent
4532 // struct has alignment larger than 1
4535 A transparent struct is supposed to be represented exactly like the piece of
4536 data it contains. Zero-sized fields with different alignment requirements
4537 potentially conflict with this property. In the example above, `Wrapper` would
4538 have to be aligned to 32 bytes even though `f32` has a smaller alignment
4541 Consider removing the over-aligned zero-sized field:
4544 #[repr(transparent)]
4545 struct Wrapper(f32);
4548 Alternatively, `PhantomData<T>` has alignment 1 for all `T`, so you can use it
4549 if you need to keep the field for some reason:
4552 #![feature(repr_align)]
4554 use std::marker::PhantomData;
4557 struct ForceAlign32;
4559 #[repr(transparent)]
4560 struct Wrapper(f32, PhantomData<ForceAlign32>);
4563 Note that empty arrays `[T; 0]` have the same alignment requirement as the
4564 element type `T`. Also note that the error is conservatively reported even when
4565 the alignment of the zero-sized type is less than or equal to the data field's
4571 A method was called on a raw pointer whose inner type wasn't completely known.
4573 For example, you may have done something like:
4576 # #![deny(warnings)]
4578 let bar = foo as *const _;
4584 Here, the type of `bar` isn't known; it could be a pointer to anything. Instead,
4585 specify a type for the pointer (preferably something that makes sense for the
4586 thing you're pointing to):
4590 let bar = foo as *const i32;
4596 Even though `is_null()` exists as a method on any raw pointer, Rust shows this
4597 error because Rust allows for `self` to have arbitrary types (behind the
4598 arbitrary_self_types feature flag).
4600 This means that someone can specify such a function:
4602 ```ignore (cannot-doctest-feature-doesnt-exist-yet)
4604 fn is_null(self: *const Self) -> bool {
4605 // do something else
4610 and now when you call `.is_null()` on a raw pointer to `Foo`, there's ambiguity.
4612 Given that we don't know what type the pointer is, and there's potential
4613 ambiguity for some types, we disallow calling methods on raw pointers when
4614 the type is unknown.
4618 A `#[marker]` trait contained an associated item.
4620 The items of marker traits cannot be overridden, so there's no need to have them
4621 when they cannot be changed per-type anyway. If you wanted them for ergonomic
4622 reasons, consider making an extension trait instead.
4626 An `impl` for a `#[marker]` trait tried to override an associated item.
4628 Because marker traits are allowed to have multiple implementations for the same
4629 type, it's not allowed to override anything in those implementations, as it
4630 would be ambiguous which override should actually be used.
4635 An `impl Trait` type expands to a recursive type.
4637 An `impl Trait` type must be expandable to a concrete type that contains no
4638 `impl Trait` types. For example the following example tries to create an
4639 `impl Trait` type `T` that is equal to `[T, T]`:
4641 ```compile_fail,E0720
4642 fn make_recursive_type() -> impl Sized {
4643 [make_recursive_type(), make_recursive_type()]
4650 register_diagnostics! {
4651 // E0035, merged into E0087/E0089
4652 // E0036, merged into E0087/E0089
4658 // E0122, // bounds in type aliases are ignored, turned into proper lint
4663 // E0159, // use of trait `{}` as struct constructor
4664 // E0163, // merged into E0071
4667 // E0172, // non-trait found in a type sum, moved to resolve
4668 // E0173, // manual implementations of unboxed closure traits are experimental
4670 // E0182, // merged into E0229
4672 // E0187, // can't infer the kind of the closure
4673 // E0188, // can not cast an immutable reference to a mutable pointer
4674 // E0189, // deprecated: can only cast a boxed pointer to a boxed object
4675 // E0190, // deprecated: can only cast a &-pointer to an &-object
4676 // E0196, // cannot determine a type for this closure
4677 E0203, // type parameter has more than one relaxed default bound,
4678 // and only one is supported
4680 // E0209, // builtin traits can only be implemented on structs or enums
4681 E0212, // cannot extract an associated type from a higher-ranked trait bound
4682 // E0213, // associated types are not accepted in this context
4683 // E0215, // angle-bracket notation is not stable with `Fn`
4684 // E0216, // parenthetical notation is only stable with `Fn`
4685 // E0217, // ambiguous associated type, defined in multiple supertraits
4686 // E0218, // no associated type defined
4687 // E0219, // associated type defined in higher-ranked supertrait
4688 // E0222, // Error code E0045 (variadic function must have C or cdecl calling
4689 // convention) duplicate
4690 E0224, // at least one non-builtin train is required for an object type
4691 E0227, // ambiguous lifetime bound, explicit lifetime bound required
4692 E0228, // explicit lifetime bound required
4695 // E0235, // structure constructor specifies a structure of type but
4696 // E0236, // no lang item for range syntax
4697 // E0237, // no lang item for range syntax
4698 // E0238, // parenthesized parameters may only be used with a trait
4699 // E0239, // `next` method of `Iterator` trait has unexpected type
4703 // E0245, // not a trait
4704 // E0246, // invalid recursive type
4706 // E0248, // value used as a type, now reported earlier during resolution as E0412
4708 E0307, // invalid method `self` type
4709 // E0319, // trait impls for defaulted traits allowed just for structs/enums
4710 // E0372, // coherence not object safe
4711 E0377, // the trait `CoerceUnsized` may only be implemented for a coercion
4712 // between structures with the same definition
4713 // E0558, // replaced with a generic attribute input check
4714 E0533, // `{}` does not name a unit variant, unit struct or a constant
4715 // E0563, // cannot determine a type for this `impl Trait`: {} // removed in 6383de15
4716 E0564, // only named lifetimes are allowed in `impl Trait`,
4717 // but `{}` was found in the type `{}`
4718 E0587, // type has conflicting packed and align representation hints
4719 E0588, // packed type cannot transitively contain a `[repr(align)]` type
4720 E0592, // duplicate definitions with name `{}`
4721 // E0611, // merged into E0616
4722 // E0612, // merged into E0609
4723 // E0613, // Removed (merged with E0609)
4724 E0627, // yield statement outside of generator literal
4725 E0632, // cannot provide explicit type parameters when `impl Trait` is used in
4726 // argument position.
4727 E0634, // type has conflicting packed representaton hints
4728 E0640, // infer outlives requirements
4729 E0641, // cannot cast to/from a pointer with an unknown kind
4730 E0645, // trait aliases not finished
4731 E0698, // type inside generator must be known in this context
4732 E0719, // duplicate values for associated type binding
4733 E0722, // Malformed #[optimize] attribute
4734 E0724, // `#[ffi_returns_twice]` is only allowed in foreign functions