1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![allow(non_snake_case)]
13 register_long_diagnostics! {
16 A pattern used to match against an enum variant must provide a sub-pattern for
17 each field of the enum variant. This error indicates that a pattern attempted to
18 extract an incorrect number of fields from a variant.
22 Apple(String, String),
27 Here the `Apple` variant has two fields, and should be matched against like so:
31 Apple(String, String),
35 let x = Fruit::Apple(String::new(), String::new());
39 Fruit::Apple(a, b) => {},
44 Matching with the wrong number of fields has no sensible interpretation:
48 Apple(String, String),
52 let x = Fruit::Apple(String::new(), String::new());
56 Fruit::Apple(a) => {},
57 Fruit::Apple(a, b, c) => {},
61 Check how many fields the enum was declared with and ensure that your pattern
66 Each field of a struct can only be bound once in a pattern. Erroneous code
76 let x = Foo { a:1, b:2 };
78 let Foo { a: x, a: y } = x;
79 // error: field `a` bound multiple times in the pattern
83 Each occurrence of a field name binds the value of that field, so to fix this
84 error you will have to remove or alter the duplicate uses of the field name.
85 Perhaps you misspelled another field name? Example:
94 let x = Foo { a:1, b:2 };
96 let Foo { a: x, b: y } = x; // ok!
102 This error indicates that a struct pattern attempted to extract a non-existent
103 field from a struct. Struct fields are identified by the name used before the
104 colon `:` so struct patterns should resemble the declaration of the struct type
114 let thing = Thing { x: 1, y: 2 };
117 Thing { x: xfield, y: yfield } => {}
121 If you are using shorthand field patterns but want to refer to the struct field
122 by a different name, you should rename it explicitly.
126 ```compile_fail,E0026
132 let thing = Thing { x: 0, y: 0 };
147 let thing = Thing { x: 0, y: 0 };
150 Thing { x, y: z } => {}
156 This error indicates that a pattern for a struct fails to specify a sub-pattern
157 for every one of the struct's fields. Ensure that each field from the struct's
158 definition is mentioned in the pattern, or use `..` to ignore unwanted fields.
162 ```compile_fail,E0027
168 let d = Dog { name: "Rusty".to_string(), age: 8 };
170 // This is incorrect.
176 This is correct (explicit):
184 let d = Dog { name: "Rusty".to_string(), age: 8 };
187 Dog { name: ref n, age: x } => {}
190 // This is also correct (ignore unused fields).
192 Dog { age: x, .. } => {}
198 In a match expression, only numbers and characters can be matched against a
199 range. This is because the compiler checks that the range is non-empty at
200 compile-time, and is unable to evaluate arbitrary comparison functions. If you
201 want to capture values of an orderable type between two end-points, you can use
204 ```compile_fail,E0029
205 let string = "salutations !";
207 // The ordering relation for strings can't be evaluated at compile time,
208 // so this doesn't work:
210 "hello" ... "world" => {}
214 // This is a more general version, using a guard:
216 s if s >= "hello" && s <= "world" => {}
223 This error indicates that a pointer to a trait type cannot be implicitly
224 dereferenced by a pattern. Every trait defines a type, but because the
225 size of trait implementors isn't fixed, this type has no compile-time size.
226 Therefore, all accesses to trait types must be through pointers. If you
227 encounter this error you should try to avoid dereferencing the pointer.
229 ```compile_fail,E0033
230 # trait SomeTrait { fn method_one(&self){} fn method_two(&self){} }
231 # impl<T> SomeTrait for T {}
232 let trait_obj: &SomeTrait = &"some_value";
234 // This tries to implicitly dereference to create an unsized local variable.
235 let &invalid = trait_obj;
237 // You can call methods without binding to the value being pointed at.
238 trait_obj.method_one();
239 trait_obj.method_two();
242 You can read more about trait objects in the [Trait Objects] section of the
245 [Trait Objects]: https://doc.rust-lang.org/reference/types.html#trait-objects
249 The compiler doesn't know what method to call because more than one method
250 has the same prototype. Erroneous code example:
252 ```compile_fail,E0034
263 impl Trait1 for Test { fn foo() {} }
264 impl Trait2 for Test { fn foo() {} }
267 Test::foo() // error, which foo() to call?
271 To avoid this error, you have to keep only one of them and remove the others.
272 So let's take our example and fix it:
281 impl Trait1 for Test { fn foo() {} }
284 Test::foo() // and now that's good!
288 However, a better solution would be using fully explicit naming of type and
302 impl Trait1 for Test { fn foo() {} }
303 impl Trait2 for Test { fn foo() {} }
306 <Test as Trait1>::foo()
323 impl F for X { fn m(&self) { println!("I am F"); } }
324 impl G for X { fn m(&self) { println!("I am G"); } }
329 F::m(&f); // it displays "I am F"
330 G::m(&f); // it displays "I am G"
336 It is not allowed to manually call destructors in Rust. It is also not
337 necessary to do this since `drop` is called automatically whenever a value goes
340 Here's an example of this error:
342 ```compile_fail,E0040
354 let mut x = Foo { x: -7 };
355 x.drop(); // error: explicit use of destructor method
361 You can't use type parameters on foreign items. Example of erroneous code:
363 ```compile_fail,E0044
364 extern { fn some_func<T>(x: T); }
367 To fix this, replace the type parameter with the specializations that you
371 extern { fn some_func_i32(x: i32); }
372 extern { fn some_func_i64(x: i64); }
377 Rust only supports variadic parameters for interoperability with C code in its
378 FFI. As such, variadic parameters can only be used with functions which are
379 using the C ABI. Examples of erroneous code:
382 #![feature(unboxed_closures)]
384 extern "rust-call" { fn foo(x: u8, ...); }
388 fn foo(x: u8, ...) {}
391 To fix such code, put them in an extern "C" block:
401 Items are missing in a trait implementation. Erroneous code example:
403 ```compile_fail,E0046
411 // error: not all trait items implemented, missing: `foo`
414 When trying to make some type implement a trait `Foo`, you must, at minimum,
415 provide implementations for all of `Foo`'s required methods (meaning the
416 methods that do not have default implementations), as well as any required
417 trait items like associated types or constants. Example:
433 This error indicates that an attempted implementation of a trait method
434 has the wrong number of type parameters.
436 For example, the trait below has a method `foo` with a type parameter `T`,
437 but the implementation of `foo` for the type `Bar` is missing this parameter:
439 ```compile_fail,E0049
441 fn foo<T: Default>(x: T) -> Self;
446 // error: method `foo` has 0 type parameters but its trait declaration has 1
449 fn foo(x: bool) -> Self { Bar }
455 This error indicates that an attempted implementation of a trait method
456 has the wrong number of function parameters.
458 For example, the trait below has a method `foo` with two function parameters
459 (`&self` and `u8`), but the implementation of `foo` for the type `Bar` omits
462 ```compile_fail,E0050
464 fn foo(&self, x: u8) -> bool;
469 // error: method `foo` has 1 parameter but the declaration in trait `Foo::foo`
472 fn foo(&self) -> bool { true }
478 The parameters of any trait method must match between a trait implementation
479 and the trait definition.
481 Here are a couple examples of this error:
483 ```compile_fail,E0053
492 // error, expected u16, found i16
495 // error, types differ in mutability
496 fn bar(&mut self) { }
502 It is not allowed to cast to a bool. If you are trying to cast a numeric type
503 to a bool, you can compare it with zero instead:
505 ```compile_fail,E0054
508 // Not allowed, won't compile
509 let x_is_nonzero = x as bool;
516 let x_is_nonzero = x != 0;
521 During a method call, a value is automatically dereferenced as many times as
522 needed to make the value's type match the method's receiver. The catch is that
523 the compiler will only attempt to dereference a number of times up to the
524 recursion limit (which can be set via the `recursion_limit` attribute).
526 For a somewhat artificial example:
528 ```compile_fail,E0055
529 #![recursion_limit="2"]
541 // error, reached the recursion limit while auto-dereferencing &&Foo
546 One fix may be to increase the recursion limit. Note that it is possible to
547 create an infinite recursion of dereferencing, in which case the only fix is to
548 somehow break the recursion.
552 When invoking closures or other implementations of the function traits `Fn`,
553 `FnMut` or `FnOnce` using call notation, the number of parameters passed to the
554 function must match its definition.
556 An example using a closure:
558 ```compile_fail,E0057
560 let a = f(); // invalid, too few parameters
561 let b = f(4); // this works!
562 let c = f(2, 3); // invalid, too many parameters
565 A generic function must be treated similarly:
568 fn foo<F: Fn()>(f: F) {
569 f(); // this is valid, but f(3) would not work
575 The built-in function traits are generic over a tuple of the function arguments.
576 If one uses angle-bracket notation (`Fn<(T,), Output=U>`) instead of parentheses
577 (`Fn(T) -> U`) to denote the function trait, the type parameter should be a
578 tuple. Otherwise function call notation cannot be used and the trait will not be
579 implemented by closures.
581 The most likely source of this error is using angle-bracket notation without
582 wrapping the function argument type into a tuple, for example:
584 ```compile_fail,E0059
585 #![feature(unboxed_closures)]
587 fn foo<F: Fn<i32>>(f: F) -> F::Output { f(3) }
590 It can be fixed by adjusting the trait bound like this:
593 #![feature(unboxed_closures)]
595 fn foo<F: Fn<(i32,)>>(f: F) -> F::Output { f(3) }
598 Note that `(T,)` always denotes the type of a 1-tuple containing an element of
599 type `T`. The comma is necessary for syntactic disambiguation.
603 External C functions are allowed to be variadic. However, a variadic function
604 takes a minimum number of arguments. For example, consider C's variadic `printf`
608 use std::os::raw::{c_char, c_int};
611 fn printf(_: *const c_char, ...) -> c_int;
615 Using this declaration, it must be called with at least one argument, so
616 simply calling `printf()` is invalid. But the following uses are allowed:
619 # #![feature(static_nobundle)]
620 # use std::os::raw::{c_char, c_int};
621 # #[cfg_attr(all(windows, target_env = "msvc"),
622 # link(name = "legacy_stdio_definitions", kind = "static-nobundle"))]
623 # extern "C" { fn printf(_: *const c_char, ...) -> c_int; }
626 use std::ffi::CString;
628 let fmt = CString::new("test\n").unwrap();
629 printf(fmt.as_ptr());
631 let fmt = CString::new("number = %d\n").unwrap();
632 printf(fmt.as_ptr(), 3);
634 let fmt = CString::new("%d, %d\n").unwrap();
635 printf(fmt.as_ptr(), 10, 5);
640 // ^ Note: On MSVC 2015, the `printf` function is "inlined" in the C code, and
641 // the C runtime does not contain the `printf` definition. This leads to linker
642 // error from the doc test (issue #42830).
643 // This can be fixed by linking to the static library
644 // `legacy_stdio_definitions.lib` (see https://stackoverflow.com/a/36504365/).
645 // If this compatibility library is removed in the future, consider changing
646 // `printf` in this example to another well-known variadic function.
649 The number of arguments passed to a function must match the number of arguments
650 specified in the function signature.
652 For example, a function like:
655 fn f(a: u16, b: &str) {}
658 Must always be called with exactly two arguments, e.g. `f(2, "test")`.
660 Note that Rust does not have a notion of optional function arguments or
661 variadic functions (except for its C-FFI).
665 This error indicates that during an attempt to build a struct or struct-like
666 enum variant, one of the fields was specified more than once. Erroneous code
669 ```compile_fail,E0062
677 x: 0, // error: field `x` specified more than once
682 Each field should be specified exactly one time. Example:
690 let x = Foo { x: 0 }; // ok!
696 This error indicates that during an attempt to build a struct or struct-like
697 enum variant, one of the fields was not provided. Erroneous code example:
699 ```compile_fail,E0063
706 let x = Foo { x: 0 }; // error: missing field: `y`
710 Each field should be specified exactly once. Example:
719 let x = Foo { x: 0, y: 0 }; // ok!
725 Box placement expressions (like C++'s "placement new") do not yet support any
726 place expression except the exchange heap (i.e. `std::boxed::HEAP`).
727 Furthermore, the syntax is changing to use `in` instead of `box`. See [RFC 470]
728 and [RFC 809] for more details.
730 [RFC 470]: https://github.com/rust-lang/rfcs/pull/470
731 [RFC 809]: https://github.com/rust-lang/rfcs/blob/master/text/0809-box-and-in-for-stdlib.md
735 The left-hand side of a compound assignment expression must be an lvalue
736 expression. An lvalue expression represents a memory location and includes
737 item paths (ie, namespaced variables), dereferences, indexing expressions,
738 and field references.
740 Let's start with some erroneous code examples:
742 ```compile_fail,E0067
743 use std::collections::LinkedList;
745 // Bad: assignment to non-lvalue expression
746 LinkedList::new() += 1;
750 fn some_func(i: &mut i32) {
751 i += 12; // Error : '+=' operation cannot be applied on a reference !
755 And now some working examples:
764 fn some_func(i: &mut i32) {
771 The compiler found a function whose body contains a `return;` statement but
772 whose return type is not `()`. An example of this is:
774 ```compile_fail,E0069
781 Since `return;` is just like `return ();`, there is a mismatch between the
782 function's return type and the value being returned.
786 The left-hand side of an assignment operator must be an lvalue expression. An
787 lvalue expression represents a memory location and can be a variable (with
788 optional namespacing), a dereference, an indexing expression or a field
791 More details can be found in the [Expressions] section of the Reference.
793 [Expressions]: https://doc.rust-lang.org/reference/expressions.html#lvalues-rvalues-and-temporaries
795 Now, we can go further. Here are some erroneous code examples:
797 ```compile_fail,E0070
803 const SOME_CONST : i32 = 12;
805 fn some_other_func() {}
808 SOME_CONST = 14; // error : a constant value cannot be changed!
809 1 = 3; // error : 1 isn't a valid lvalue!
810 some_other_func() = 4; // error : we can't assign value to a function!
811 SomeStruct.x = 12; // error : SomeStruct a structure name but it is used
816 And now let's give working examples:
823 let mut s = SomeStruct {x: 0, y: 0};
825 s.x = 3; // that's good !
829 fn some_func(x: &mut i32) {
830 *x = 12; // that's good !
836 You tried to use structure-literal syntax to create an item that is
837 not a structure or enum variant.
839 Example of erroneous code:
841 ```compile_fail,E0071
843 let t = U32 { value: 4 }; // error: expected struct, variant or union type,
844 // found builtin type `u32`
847 To fix this, ensure that the name was correctly spelled, and that
848 the correct form of initializer was used.
850 For example, the code above can be fixed to:
858 let u = Foo::FirstValue(0i32);
866 #### Note: this error code is no longer emitted by the compiler.
868 You cannot define a struct (or enum) `Foo` that requires an instance of `Foo`
869 in order to make a new `Foo` value. This is because there would be no way a
870 first instance of `Foo` could be made to initialize another instance!
872 Here's an example of a struct that has this problem:
875 struct Foo { x: Box<Foo> } // error
878 One fix is to use `Option`, like so:
881 struct Foo { x: Option<Box<Foo>> }
884 Now it's possible to create at least one instance of `Foo`: `Foo { x: None }`.
888 #### Note: this error code is no longer emitted by the compiler.
890 When using the `#[simd]` attribute on a tuple struct, the components of the
891 tuple struct must all be of a concrete, nongeneric type so the compiler can
892 reason about how to use SIMD with them. This error will occur if the types
895 This will cause an error:
898 #![feature(repr_simd)]
901 struct Bad<T>(T, T, T);
907 #![feature(repr_simd)]
910 struct Good(u32, u32, u32);
915 The `#[simd]` attribute can only be applied to non empty tuple structs, because
916 it doesn't make sense to try to use SIMD operations when there are no values to
919 This will cause an error:
921 ```compile_fail,E0075
922 #![feature(repr_simd)]
931 #![feature(repr_simd)]
939 When using the `#[simd]` attribute to automatically use SIMD operations in tuple
940 struct, the types in the struct must all be of the same type, or the compiler
941 will trigger this error.
943 This will cause an error:
945 ```compile_fail,E0076
946 #![feature(repr_simd)]
949 struct Bad(u16, u32, u32);
955 #![feature(repr_simd)]
958 struct Good(u32, u32, u32);
963 When using the `#[simd]` attribute on a tuple struct, the elements in the tuple
964 must be machine types so SIMD operations can be applied to them.
966 This will cause an error:
968 ```compile_fail,E0077
969 #![feature(repr_simd)]
978 #![feature(repr_simd)]
981 struct Good(u32, u32, u32);
986 Enum discriminants are used to differentiate enum variants stored in memory.
987 This error indicates that the same value was used for two or more variants,
988 making them impossible to tell apart.
990 ```compile_fail,E0081
1008 Note that variants without a manually specified discriminant are numbered from
1009 top to bottom starting from 0, so clashes can occur with seemingly unrelated
1012 ```compile_fail,E0081
1019 Here `X` will have already been specified the discriminant 0 by the time `Y` is
1020 encountered, so a conflict occurs.
1024 #### Note: this error code is no longer emitted by the compiler.
1026 When you specify enum discriminants with `=`, the compiler expects `isize`
1027 values by default. Or you can add the `repr` attibute to the enum declaration
1028 for an explicit choice of the discriminant type. In either cases, the
1029 discriminant values must fall within a valid range for the expected type;
1030 otherwise this error is raised. For example:
1033 # #![deny(overflowing_literals)]
1041 Here, 1024 lies outside the valid range for `u8`, so the discriminant for `A` is
1042 invalid. Here is another, more subtle example which depends on target word size:
1044 ```compile_fail,E0080
1046 enum DependsOnPointerSize {
1051 Here, `1 << 32` is interpreted as an `isize` value. So it is invalid for 32 bit
1052 target (`target_pointer_width = "32"`) but valid for 64 bit target.
1054 You may want to change representation types to fix this, or else change invalid
1055 discriminant values so that they fit within the existing type.
1059 An unsupported representation was attempted on a zero-variant enum.
1061 Erroneous code example:
1063 ```compile_fail,E0084
1065 enum NightsWatch {} // error: unsupported representation for zero-variant enum
1068 It is impossible to define an integer type to be used to represent zero-variant
1069 enum values because there are no zero-variant enum values. There is no way to
1070 construct an instance of the following type using only safe code. So you have
1071 two solutions. Either you add variants in your enum:
1081 or you remove the integer represention of your enum:
1089 Too many type parameters were supplied for a function. For example:
1091 ```compile_fail,E0087
1095 foo::<f64, bool>(); // error, expected 1 parameter, found 2 parameters
1099 The number of supplied parameters must exactly match the number of defined type
1104 You gave too many lifetime parameters. Erroneous code example:
1106 ```compile_fail,E0088
1110 f::<'static>() // error: too many lifetime parameters provided
1114 Please check you give the right number of lifetime parameters. Example:
1124 It's also important to note that the Rust compiler can generally
1125 determine the lifetime by itself. Example:
1133 // it can be written like this
1134 fn get_value<'a>(&'a self) -> &'a str { &self.value }
1135 // but the compiler works fine with this too:
1136 fn without_lifetime(&self) -> &str { &self.value }
1140 let f = Foo { value: "hello".to_owned() };
1142 println!("{}", f.get_value());
1143 println!("{}", f.without_lifetime());
1149 Not enough type parameters were supplied for a function. For example:
1151 ```compile_fail,E0089
1155 foo::<f64>(); // error, expected 2 parameters, found 1 parameter
1159 Note that if a function takes multiple type parameters but you want the compiler
1160 to infer some of them, you can use type placeholders:
1162 ```compile_fail,E0089
1163 fn foo<T, U>(x: T) {}
1167 foo::<f64>(x); // error, expected 2 parameters, found 1 parameter
1168 foo::<_, f64>(x); // same as `foo::<bool, f64>(x)`
1174 You gave too few lifetime parameters. Example:
1176 ```compile_fail,E0090
1177 fn foo<'a: 'b, 'b: 'a>() {}
1180 foo::<'static>(); // error, expected 2 lifetime parameters
1184 Please check you give the right number of lifetime parameters. Example:
1187 fn foo<'a: 'b, 'b: 'a>() {}
1190 foo::<'static, 'static>();
1196 You gave an unnecessary type parameter in a type alias. Erroneous code
1199 ```compile_fail,E0091
1200 type Foo<T> = u32; // error: type parameter `T` is unused
1202 type Foo<A,B> = Box<A>; // error: type parameter `B` is unused
1205 Please check you didn't write too many type parameters. Example:
1208 type Foo = u32; // ok!
1209 type Foo2<A> = Box<A>; // ok!
1214 You tried to declare an undefined atomic operation function.
1215 Erroneous code example:
1217 ```compile_fail,E0092
1218 #![feature(intrinsics)]
1220 extern "rust-intrinsic" {
1221 fn atomic_foo(); // error: unrecognized atomic operation
1226 Please check you didn't make a mistake in the function's name. All intrinsic
1227 functions are defined in librustc_trans/trans/intrinsic.rs and in
1228 libcore/intrinsics.rs in the Rust source code. Example:
1231 #![feature(intrinsics)]
1233 extern "rust-intrinsic" {
1234 fn atomic_fence(); // ok!
1240 You declared an unknown intrinsic function. Erroneous code example:
1242 ```compile_fail,E0093
1243 #![feature(intrinsics)]
1245 extern "rust-intrinsic" {
1246 fn foo(); // error: unrecognized intrinsic function: `foo`
1256 Please check you didn't make a mistake in the function's name. All intrinsic
1257 functions are defined in librustc_trans/trans/intrinsic.rs and in
1258 libcore/intrinsics.rs in the Rust source code. Example:
1261 #![feature(intrinsics)]
1263 extern "rust-intrinsic" {
1264 fn atomic_fence(); // ok!
1276 You gave an invalid number of type parameters to an intrinsic function.
1277 Erroneous code example:
1279 ```compile_fail,E0094
1280 #![feature(intrinsics)]
1282 extern "rust-intrinsic" {
1283 fn size_of<T, U>() -> usize; // error: intrinsic has wrong number
1284 // of type parameters
1288 Please check that you provided the right number of type parameters
1289 and verify with the function declaration in the Rust source code.
1293 #![feature(intrinsics)]
1295 extern "rust-intrinsic" {
1296 fn size_of<T>() -> usize; // ok!
1302 This error means that an incorrect number of lifetime parameters were provided
1303 for a type (like a struct or enum) or trait:
1305 ```compile_fail,E0107
1306 struct Foo<'a, 'b>(&'a str, &'b str);
1307 enum Bar { A, B, C }
1310 foo: Foo<'a>, // error: expected 2, found 1
1311 bar: Bar<'a>, // error: expected 0, found 1
1317 You tried to give a type parameter to a type which doesn't need it. Erroneous
1320 ```compile_fail,E0109
1321 type X = u32<i32>; // error: type parameters are not allowed on this type
1324 Please check that you used the correct type and recheck its definition. Perhaps
1325 it doesn't need the type parameter.
1330 type X = u32; // this compiles
1333 Note that type parameters for enum-variant constructors go after the variant,
1334 not after the enum (`Option::None::<u32>`, not `Option::<u32>::None`).
1338 You tried to give a lifetime parameter to a type which doesn't need it.
1339 Erroneous code example:
1341 ```compile_fail,E0110
1342 type X = u32<'static>; // error: lifetime parameters are not allowed on
1346 Please check that the correct type was used and recheck its definition; perhaps
1347 it doesn't need the lifetime parameter. Example:
1350 type X = u32; // ok!
1355 You can only define an inherent implementation for a type in the same crate
1356 where the type was defined. For example, an `impl` block as below is not allowed
1357 since `Vec` is defined in the standard library:
1359 ```compile_fail,E0116
1360 impl Vec<u8> { } // error
1363 To fix this problem, you can do either of these things:
1365 - define a trait that has the desired associated functions/types/constants and
1366 implement the trait for the type in question
1367 - define a new type wrapping the type and define an implementation on the new
1370 Note that using the `type` keyword does not work here because `type` only
1371 introduces a type alias:
1373 ```compile_fail,E0116
1374 type Bytes = Vec<u8>;
1376 impl Bytes { } // error, same as above
1381 This error indicates a violation of one of Rust's orphan rules for trait
1382 implementations. The rule prohibits any implementation of a foreign trait (a
1383 trait defined in another crate) where
1385 - the type that is implementing the trait is foreign
1386 - all of the parameters being passed to the trait (if there are any) are also
1389 Here's one example of this error:
1391 ```compile_fail,E0117
1392 impl Drop for u32 {}
1395 To avoid this kind of error, ensure that at least one local type is referenced
1399 pub struct Foo; // you define your type in your crate
1401 impl Drop for Foo { // and you can implement the trait on it!
1402 // code of trait implementation here
1403 # fn drop(&mut self) { }
1406 impl From<Foo> for i32 { // or you use a type from your crate as
1408 fn from(i: Foo) -> i32 {
1414 Alternatively, define a trait locally and implement that instead:
1418 fn get(&self) -> usize;
1422 fn get(&self) -> usize { 0 }
1426 For information on the design of the orphan rules, see [RFC 1023].
1428 [RFC 1023]: https://github.com/rust-lang/rfcs/blob/master/text/1023-rebalancing-coherence.md
1432 You're trying to write an inherent implementation for something which isn't a
1433 struct nor an enum. Erroneous code example:
1435 ```compile_fail,E0118
1436 impl (u8, u8) { // error: no base type found for inherent implementation
1437 fn get_state(&self) -> String {
1443 To fix this error, please implement a trait on the type or wrap it in a struct.
1447 // we create a trait here
1448 trait LiveLongAndProsper {
1449 fn get_state(&self) -> String;
1452 // and now you can implement it on (u8, u8)
1453 impl LiveLongAndProsper for (u8, u8) {
1454 fn get_state(&self) -> String {
1455 "He's dead, Jim!".to_owned()
1460 Alternatively, you can create a newtype. A newtype is a wrapping tuple-struct.
1461 For example, `NewType` is a newtype over `Foo` in `struct NewType(Foo)`.
1465 struct TypeWrapper((u8, u8));
1468 fn get_state(&self) -> String {
1469 "Fascinating!".to_owned()
1476 An attempt was made to implement Drop on a trait, which is not allowed: only
1477 structs and enums can implement Drop. An example causing this error:
1479 ```compile_fail,E0120
1482 impl Drop for MyTrait {
1483 fn drop(&mut self) {}
1487 A workaround for this problem is to wrap the trait up in a struct, and implement
1488 Drop on that. An example is shown below:
1492 struct MyWrapper<T: MyTrait> { foo: T }
1494 impl <T: MyTrait> Drop for MyWrapper<T> {
1495 fn drop(&mut self) {}
1500 Alternatively, wrapping trait objects requires something like the following:
1505 //or Box<MyTrait>, if you wanted an owned trait object
1506 struct MyWrapper<'a> { foo: &'a MyTrait }
1508 impl <'a> Drop for MyWrapper<'a> {
1509 fn drop(&mut self) {}
1515 In order to be consistent with Rust's lack of global type inference, type
1516 placeholders are disallowed by design in item signatures.
1518 Examples of this error include:
1520 ```compile_fail,E0121
1521 fn foo() -> _ { 5 } // error, explicitly write out the return type instead
1523 static BAR: _ = "test"; // error, explicitly write out the type instead
1528 An attempt was made to add a generic constraint to a type alias. This constraint
1529 is entirely ignored. For backwards compatibility, Rust still allows this with a
1530 warning. Consider the example below:
1535 type MyType<R: Foo> = (R, ());
1542 We're able to declare a variable of type `MyType<u32>`, despite the fact that
1543 `u32` does not implement `Foo`. As a result, one should avoid using generic
1544 constraints in concert with type aliases.
1548 You declared two fields of a struct with the same name. Erroneous code
1551 ```compile_fail,E0124
1554 field1: i32, // error: field is already declared
1558 Please verify that the field names have been correctly spelled. Example:
1569 It is not possible to define `main` with type parameters, or even with function
1570 parameters. When `main` is present, it must take no arguments and return `()`.
1571 Erroneous code example:
1573 ```compile_fail,E0131
1574 fn main<T>() { // error: main function is not allowed to have type parameters
1580 A function with the `start` attribute was declared with type parameters.
1582 Erroneous code example:
1584 ```compile_fail,E0132
1591 It is not possible to declare type parameters on a function that has the `start`
1592 attribute. Such a function must have the following type signature (for more
1593 information: http://doc.rust-lang.org/stable/book/first-edition/no-stdlib.html):
1597 fn(isize, *const *const u8) -> isize;
1606 fn my_start(argc: isize, argv: *const *const u8) -> isize {
1613 This error means that an attempt was made to match a struct type enum
1614 variant as a non-struct type:
1616 ```compile_fail,E0164
1617 enum Foo { B { i: u32 } }
1619 fn bar(foo: Foo) -> u32 {
1621 Foo::B(i) => i, // error E0164
1626 Try using `{}` instead:
1629 enum Foo { B { i: u32 } }
1631 fn bar(foo: Foo) -> u32 {
1640 Explicitly implementing both Drop and Copy for a type is currently disallowed.
1641 This feature can make some sense in theory, but the current implementation is
1642 incorrect and can lead to memory unsafety (see [issue #20126][iss20126]), so
1643 it has been disabled for now.
1645 [iss20126]: https://github.com/rust-lang/rust/issues/20126
1649 An associated function for a trait was defined to be static, but an
1650 implementation of the trait declared the same function to be a method (i.e. to
1651 take a `self` parameter).
1653 Here's an example of this error:
1655 ```compile_fail,E0185
1663 // error, method `foo` has a `&self` declaration in the impl, but not in
1671 An associated function for a trait was defined to be a method (i.e. to take a
1672 `self` parameter), but an implementation of the trait declared the same function
1675 Here's an example of this error:
1677 ```compile_fail,E0186
1685 // error, method `foo` has a `&self` declaration in the trait, but not in
1693 Trait objects need to have all associated types specified. Erroneous code
1696 ```compile_fail,E0191
1701 type Foo = Trait; // error: the value of the associated type `Bar` (from
1702 // the trait `Trait`) must be specified
1705 Please verify you specified all associated types of the trait and that you
1706 used the right trait. Example:
1713 type Foo = Trait<Bar=i32>; // ok!
1718 Negative impls are only allowed for traits with default impls. For more
1719 information see the [opt-in builtin traits RFC][RFC 19].
1721 [RFC 19]: https://github.com/rust-lang/rfcs/blob/master/text/0019-opt-in-builtin-traits.md
1725 #### Note: this error code is no longer emitted by the compiler.
1727 `where` clauses must use generic type parameters: it does not make sense to use
1728 them otherwise. An example causing this error:
1735 #[derive(Copy,Clone)]
1740 impl Foo for Wrapper<u32> where Wrapper<u32>: Clone {
1745 This use of a `where` clause is strange - a more common usage would look
1746 something like the following:
1753 #[derive(Copy,Clone)]
1757 impl <T> Foo for Wrapper<T> where Wrapper<T>: Clone {
1762 Here, we're saying that the implementation exists on Wrapper only when the
1763 wrapped type `T` implements `Clone`. The `where` clause is important because
1764 some types will not implement `Clone`, and thus will not get this method.
1766 In our erroneous example, however, we're referencing a single concrete type.
1767 Since we know for certain that `Wrapper<u32>` implements `Clone`, there's no
1768 reason to also specify it in a `where` clause.
1772 A type parameter was declared which shadows an existing one. An example of this
1775 ```compile_fail,E0194
1777 fn do_something(&self) -> T;
1778 fn do_something_else<T: Clone>(&self, bar: T);
1782 In this example, the trait `Foo` and the trait method `do_something_else` both
1783 define a type parameter `T`. This is not allowed: if the method wishes to
1784 define a type parameter, it must use a different name for it.
1788 Your method's lifetime parameters do not match the trait declaration.
1789 Erroneous code example:
1791 ```compile_fail,E0195
1793 fn bar<'a,'b:'a>(x: &'a str, y: &'b str);
1798 impl Trait for Foo {
1799 fn bar<'a,'b>(x: &'a str, y: &'b str) {
1800 // error: lifetime parameters or bounds on method `bar`
1801 // do not match the trait declaration
1806 The lifetime constraint `'b` for bar() implementation does not match the
1807 trait declaration. Ensure lifetime declarations match exactly in both trait
1808 declaration and implementation. Example:
1812 fn t<'a,'b:'a>(x: &'a str, y: &'b str);
1817 impl Trait for Foo {
1818 fn t<'a,'b:'a>(x: &'a str, y: &'b str) { // ok!
1825 Inherent implementations (one that do not implement a trait but provide
1826 methods associated with a type) are always safe because they are not
1827 implementing an unsafe trait. Removing the `unsafe` keyword from the inherent
1828 implementation will resolve this error.
1830 ```compile_fail,E0197
1833 // this will cause this error
1835 // converting it to this will fix it
1841 A negative implementation is one that excludes a type from implementing a
1842 particular trait. Not being able to use a trait is always a safe operation,
1843 so negative implementations are always safe and never need to be marked as
1847 #![feature(optin_builtin_traits)]
1851 // unsafe is unnecessary
1852 unsafe impl !Clone for Foo { }
1858 #![feature(optin_builtin_traits)]
1864 impl Enterprise for .. { }
1866 impl !Enterprise for Foo { }
1869 Please note that negative impls are only allowed for traits with default impls.
1873 Safe traits should not have unsafe implementations, therefore marking an
1874 implementation for a safe trait unsafe will cause a compiler error. Removing
1875 the unsafe marker on the trait noted in the error will resolve this problem.
1877 ```compile_fail,E0199
1882 // this won't compile because Bar is safe
1883 unsafe impl Bar for Foo { }
1884 // this will compile
1885 impl Bar for Foo { }
1890 Unsafe traits must have unsafe implementations. This error occurs when an
1891 implementation for an unsafe trait isn't marked as unsafe. This may be resolved
1892 by marking the unsafe implementation as unsafe.
1894 ```compile_fail,E0200
1897 unsafe trait Bar { }
1899 // this won't compile because Bar is unsafe and impl isn't unsafe
1900 impl Bar for Foo { }
1901 // this will compile
1902 unsafe impl Bar for Foo { }
1907 It is an error to define two associated items (like methods, associated types,
1908 associated functions, etc.) with the same identifier.
1912 ```compile_fail,E0201
1916 fn bar(&self) -> bool { self.0 > 5 }
1917 fn bar() {} // error: duplicate associated function
1922 fn baz(&self) -> bool;
1928 fn baz(&self) -> bool { true }
1930 // error: duplicate method
1931 fn baz(&self) -> bool { self.0 > 5 }
1933 // error: duplicate associated type
1938 Note, however, that items with the same name are allowed for inherent `impl`
1939 blocks that don't overlap:
1945 fn bar(&self) -> bool { self.0 > 5 }
1949 fn bar(&self) -> bool { self.0 }
1955 Inherent associated types were part of [RFC 195] but are not yet implemented.
1956 See [the tracking issue][iss8995] for the status of this implementation.
1958 [RFC 195]: https://github.com/rust-lang/rfcs/blob/master/text/0195-associated-items.md
1959 [iss8995]: https://github.com/rust-lang/rust/issues/8995
1963 An attempt to implement the `Copy` trait for a struct failed because one of the
1964 fields does not implement `Copy`. To fix this, you must implement `Copy` for the
1965 mentioned field. Note that this may not be possible, as in the example of
1967 ```compile_fail,E0204
1972 impl Copy for Foo { }
1975 This fails because `Vec<T>` does not implement `Copy` for any `T`.
1977 Here's another example that will fail:
1979 ```compile_fail,E0204
1986 This fails because `&mut T` is not `Copy`, even when `T` is `Copy` (this
1987 differs from the behavior for `&T`, which is always `Copy`).
1992 An attempt to implement the `Copy` trait for an enum failed because one of the
1993 variants does not implement `Copy`. To fix this, you must implement `Copy` for
1994 the mentioned variant. Note that this may not be possible, as in the example of
1996 ```compile_fail,E0205
2002 impl Copy for Foo { }
2005 This fails because `Vec<T>` does not implement `Copy` for any `T`.
2007 Here's another example that will fail:
2009 ```compile_fail,E0205
2017 This fails because `&mut T` is not `Copy`, even when `T` is `Copy` (this
2018 differs from the behavior for `&T`, which is always `Copy`).
2023 You can only implement `Copy` for a struct or enum. Both of the following
2024 examples will fail, because neither `i32` (primitive type) nor `&'static Bar`
2025 (reference to `Bar`) is a struct or enum:
2027 ```compile_fail,E0206
2029 impl Copy for Foo { } // error
2031 #[derive(Copy, Clone)]
2033 impl Copy for &'static Bar { } // error
2038 Any type parameter or lifetime parameter of an `impl` must meet at least one of
2039 the following criteria:
2041 - it appears in the self type of the impl
2042 - for a trait impl, it appears in the trait reference
2043 - it is bound as an associated type
2047 Suppose we have a struct `Foo` and we would like to define some methods for it.
2048 The following definition leads to a compiler error:
2050 ```compile_fail,E0207
2053 impl<T: Default> Foo {
2054 // error: the type parameter `T` is not constrained by the impl trait, self
2055 // type, or predicates [E0207]
2056 fn get(&self) -> T {
2057 <T as Default>::default()
2062 The problem is that the parameter `T` does not appear in the self type (`Foo`)
2063 of the impl. In this case, we can fix the error by moving the type parameter
2064 from the `impl` to the method `get`:
2070 // Move the type parameter from the impl to the method
2072 fn get<T: Default>(&self) -> T {
2073 <T as Default>::default()
2080 As another example, suppose we have a `Maker` trait and want to establish a
2081 type `FooMaker` that makes `Foo`s:
2083 ```compile_fail,E0207
2086 fn make(&mut self) -> Self::Item;
2095 impl<T: Default> Maker for FooMaker {
2096 // error: the type parameter `T` is not constrained by the impl trait, self
2097 // type, or predicates [E0207]
2100 fn make(&mut self) -> Foo<T> {
2101 Foo { foo: <T as Default>::default() }
2106 This fails to compile because `T` does not appear in the trait or in the
2109 One way to work around this is to introduce a phantom type parameter into
2110 `FooMaker`, like so:
2113 use std::marker::PhantomData;
2117 fn make(&mut self) -> Self::Item;
2124 // Add a type parameter to `FooMaker`
2125 struct FooMaker<T> {
2126 phantom: PhantomData<T>,
2129 impl<T: Default> Maker for FooMaker<T> {
2132 fn make(&mut self) -> Foo<T> {
2134 foo: <T as Default>::default(),
2140 Another way is to do away with the associated type in `Maker` and use an input
2141 type parameter instead:
2144 // Use a type parameter instead of an associated type here
2146 fn make(&mut self) -> Item;
2155 impl<T: Default> Maker<Foo<T>> for FooMaker {
2156 fn make(&mut self) -> Foo<T> {
2157 Foo { foo: <T as Default>::default() }
2162 ### Additional information
2164 For more information, please see [RFC 447].
2166 [RFC 447]: https://github.com/rust-lang/rfcs/blob/master/text/0447-no-unused-impl-parameters.md
2170 This error indicates a violation of one of Rust's orphan rules for trait
2171 implementations. The rule concerns the use of type parameters in an
2172 implementation of a foreign trait (a trait defined in another crate), and
2173 states that type parameters must be "covered" by a local type. To understand
2174 what this means, it is perhaps easiest to consider a few examples.
2176 If `ForeignTrait` is a trait defined in some external crate `foo`, then the
2177 following trait `impl` is an error:
2179 ```compile_fail,E0210
2180 # #[cfg(for_demonstration_only)]
2182 # #[cfg(for_demonstration_only)]
2183 use foo::ForeignTrait;
2184 # use std::panic::UnwindSafe as ForeignTrait;
2186 impl<T> ForeignTrait for T { } // error
2190 To work around this, it can be covered with a local type, `MyType`:
2193 # use std::panic::UnwindSafe as ForeignTrait;
2194 struct MyType<T>(T);
2195 impl<T> ForeignTrait for MyType<T> { } // Ok
2198 Please note that a type alias is not sufficient.
2200 For another example of an error, suppose there's another trait defined in `foo`
2201 named `ForeignTrait2` that takes two type parameters. Then this `impl` results
2202 in the same rule violation:
2204 ```ignore (cannot-doctest-multicrate-project)
2206 impl<T> ForeignTrait2<T, MyType<T>> for MyType2 { } // error
2209 The reason for this is that there are two appearances of type parameter `T` in
2210 the `impl` header, both as parameters for `ForeignTrait2`. The first appearance
2211 is uncovered, and so runs afoul of the orphan rule.
2213 Consider one more example:
2215 ```ignore (cannot-doctest-multicrate-project)
2216 impl<T> ForeignTrait2<MyType<T>, T> for MyType2 { } // Ok
2219 This only differs from the previous `impl` in that the parameters `T` and
2220 `MyType<T>` for `ForeignTrait2` have been swapped. This example does *not*
2221 violate the orphan rule; it is permitted.
2223 To see why that last example was allowed, you need to understand the general
2224 rule. Unfortunately this rule is a bit tricky to state. Consider an `impl`:
2226 ```ignore (only-for-syntax-highlight)
2227 impl<P1, ..., Pm> ForeignTrait<T1, ..., Tn> for T0 { ... }
2230 where `P1, ..., Pm` are the type parameters of the `impl` and `T0, ..., Tn`
2231 are types. One of the types `T0, ..., Tn` must be a local type (this is another
2232 orphan rule, see the explanation for E0117). Let `i` be the smallest integer
2233 such that `Ti` is a local type. Then no type parameter can appear in any of the
2236 For information on the design of the orphan rules, see [RFC 1023].
2238 [RFC 1023]: https://github.com/rust-lang/rfcs/blob/master/text/1023-rebalancing-coherence.md
2243 You used a function or type which doesn't fit the requirements for where it was
2244 used. Erroneous code examples:
2247 #![feature(intrinsics)]
2249 extern "rust-intrinsic" {
2250 fn size_of<T>(); // error: intrinsic has wrong type
2255 fn main() -> i32 { 0 }
2256 // error: main function expects type: `fn() {main}`: expected (), found i32
2263 // error: mismatched types in range: expected u8, found i8
2273 fn x(self: Rc<Foo>) {}
2274 // error: mismatched self type: expected `Foo`: expected struct
2275 // `Foo`, found struct `alloc::rc::Rc`
2279 For the first code example, please check the function definition. Example:
2282 #![feature(intrinsics)]
2284 extern "rust-intrinsic" {
2285 fn size_of<T>() -> usize; // ok!
2289 The second case example is a bit particular : the main function must always
2290 have this definition:
2296 They never take parameters and never return types.
2298 For the third example, when you match, all patterns must have the same type
2299 as the type you're matching on. Example:
2305 0u8...3u8 => (), // ok!
2310 And finally, for the last example, only `Box<Self>`, `&Self`, `Self`,
2311 or `&mut Self` work as explicit self parameters. Example:
2317 fn x(self: Box<Foo>) {} // ok!
2324 You used an associated type which isn't defined in the trait.
2325 Erroneous code example:
2327 ```compile_fail,E0220
2332 type Foo = T1<F=i32>; // error: associated type `F` not found for `T1`
2339 // error: Baz is used but not declared
2340 fn return_bool(&self, _: &Self::Bar, _: &Self::Baz) -> bool;
2344 Make sure that you have defined the associated type in the trait body.
2345 Also, verify that you used the right trait or you didn't misspell the
2346 associated type name. Example:
2353 type Foo = T1<Bar=i32>; // ok!
2359 type Baz; // we declare `Baz` in our trait.
2361 // and now we can use it here:
2362 fn return_bool(&self, _: &Self::Bar, _: &Self::Baz) -> bool;
2368 An attempt was made to retrieve an associated type, but the type was ambiguous.
2371 ```compile_fail,E0221
2387 In this example, `Foo` defines an associated type `A`. `Bar` inherits that type
2388 from `Foo`, and defines another associated type of the same name. As a result,
2389 when we attempt to use `Self::A`, it's ambiguous whether we mean the `A` defined
2390 by `Foo` or the one defined by `Bar`.
2392 There are two options to work around this issue. The first is simply to rename
2393 one of the types. Alternatively, one can specify the intended type using the
2407 let _: <Self as Bar>::A;
2414 An attempt was made to retrieve an associated type, but the type was ambiguous.
2417 ```compile_fail,E0223
2418 trait MyTrait {type X; }
2421 let foo: MyTrait::X;
2425 The problem here is that we're attempting to take the type of X from MyTrait.
2426 Unfortunately, the type of X is not defined, because it's only made concrete in
2427 implementations of the trait. A working version of this code might look like:
2430 trait MyTrait {type X; }
2433 impl MyTrait for MyStruct {
2438 let foo: <MyStruct as MyTrait>::X;
2442 This syntax specifies that we want the X type from MyTrait, as made concrete in
2443 MyStruct. The reason that we cannot simply use `MyStruct::X` is that MyStruct
2444 might implement two different traits with identically-named associated types.
2445 This syntax allows disambiguation between the two.
2449 You attempted to use multiple types as bounds for a closure or trait object.
2450 Rust does not currently support this. A simple example that causes this error:
2452 ```compile_fail,E0225
2454 let _: Box<std::io::Read + std::io::Write>;
2458 Send and Sync are an exception to this rule: it's possible to have bounds of
2459 one non-builtin trait, plus either or both of Send and Sync. For example, the
2460 following compiles correctly:
2464 let _: Box<std::io::Read + Send + Sync>;
2470 An associated type binding was done outside of the type parameter declaration
2471 and `where` clause. Erroneous code example:
2473 ```compile_fail,E0229
2476 fn boo(&self) -> <Self as Foo>::A;
2481 impl Foo for isize {
2483 fn boo(&self) -> usize { 42 }
2486 fn baz<I>(x: &<I as Foo<A=Bar>>::A) {}
2487 // error: associated type bindings are not allowed here
2490 To solve this error, please move the type bindings in the type parameter
2495 # trait Foo { type A; }
2496 fn baz<I: Foo<A=Bar>>(x: &<I as Foo>::A) {} // ok!
2499 Or in the `where` clause:
2503 # trait Foo { type A; }
2504 fn baz<I>(x: &<I as Foo>::A) where I: Foo<A=Bar> {}
2509 This error indicates that not enough type parameters were found in a type or
2512 For example, the `Foo` struct below is defined to be generic in `T`, but the
2513 type parameter is missing in the definition of `Bar`:
2515 ```compile_fail,E0243
2516 struct Foo<T> { x: T }
2518 struct Bar { x: Foo }
2523 This error indicates that too many type parameters were found in a type or
2526 For example, the `Foo` struct below has no type parameters, but is supplied
2527 with two in the definition of `Bar`:
2529 ```compile_fail,E0244
2530 struct Foo { x: bool }
2532 struct Bar<S, T> { x: Foo<S, T> }
2537 Default impls for a trait must be located in the same crate where the trait was
2538 defined. For more information see the [opt-in builtin traits RFC][RFC 19].
2540 [RFC 19]: https://github.com/rust-lang/rfcs/blob/master/text/0019-opt-in-builtin-traits.md
2544 A cross-crate opt-out trait was implemented on something which wasn't a struct
2545 or enum type. Erroneous code example:
2547 ```compile_fail,E0321
2548 #![feature(optin_builtin_traits)]
2552 impl !Sync for Foo {}
2554 unsafe impl Send for &'static Foo {}
2555 // error: cross-crate traits with a default impl, like `core::marker::Send`,
2556 // can only be implemented for a struct/enum type, not
2560 Only structs and enums are permitted to impl Send, Sync, and other opt-out
2561 trait, and the struct or enum must be local to the current crate. So, for
2562 example, `unsafe impl Send for Rc<Foo>` is not allowed.
2566 The `Sized` trait is a special trait built-in to the compiler for types with a
2567 constant size known at compile-time. This trait is automatically implemented
2568 for types as needed by the compiler, and it is currently disallowed to
2569 explicitly implement it for a type.
2573 An associated const was implemented when another trait item was expected.
2574 Erroneous code example:
2576 ```compile_fail,E0323
2585 // error: item `N` is an associated const, which doesn't match its
2586 // trait `<Bar as Foo>`
2590 Please verify that the associated const wasn't misspelled and the correct trait
2591 was implemented. Example:
2601 type N = u32; // ok!
2615 const N : u32 = 0; // ok!
2621 A method was implemented when another trait item was expected. Erroneous
2624 ```compile_fail,E0324
2635 // error: item `N` is an associated method, which doesn't match its
2636 // trait `<Bar as Foo>`
2640 To fix this error, please verify that the method name wasn't misspelled and
2641 verify that you are indeed implementing the correct trait items. Example:
2661 An associated type was implemented when another trait item was expected.
2662 Erroneous code example:
2664 ```compile_fail,E0325
2673 // error: item `N` is an associated type, which doesn't match its
2674 // trait `<Bar as Foo>`
2678 Please verify that the associated type name wasn't misspelled and your
2679 implementation corresponds to the trait definition. Example:
2689 type N = u32; // ok!
2703 const N : u32 = 0; // ok!
2709 The types of any associated constants in a trait implementation must match the
2710 types in the trait definition. This error indicates that there was a mismatch.
2712 Here's an example of this error:
2714 ```compile_fail,E0326
2722 const BAR: u32 = 5; // error, expected bool, found u32
2728 The Unsize trait should not be implemented directly. All implementations of
2729 Unsize are provided automatically by the compiler.
2731 Erroneous code example:
2733 ```compile_fail,E0328
2736 use std::marker::Unsize;
2740 impl<T> Unsize<T> for MyType {}
2743 If you are defining your own smart pointer type and would like to enable
2744 conversion from a sized to an unsized type with the
2745 [DST coercion system][RFC 982], use [`CoerceUnsized`] instead.
2748 #![feature(coerce_unsized)]
2750 use std::ops::CoerceUnsized;
2752 pub struct MyType<T: ?Sized> {
2753 field_with_unsized_type: T,
2756 impl<T, U> CoerceUnsized<MyType<U>> for MyType<T>
2757 where T: CoerceUnsized<U> {}
2760 [RFC 982]: https://github.com/rust-lang/rfcs/blob/master/text/0982-dst-coercion.md
2761 [`CoerceUnsized`]: https://doc.rust-lang.org/std/ops/trait.CoerceUnsized.html
2765 // Associated consts can now be accessed through generic type parameters, and
2766 // this error is no longer emitted.
2768 // FIXME: consider whether to leave it in the error index, or remove it entirely
2769 // as associated consts is not stabilized yet.
2772 An attempt was made to access an associated constant through either a generic
2773 type parameter or `Self`. This is not supported yet. An example causing this
2774 error is shown below:
2783 impl Foo for MyStruct {
2784 const BAR: f64 = 0f64;
2787 fn get_bar_bad<F: Foo>(t: F) -> f64 {
2792 Currently, the value of `BAR` for a particular type can only be accessed
2793 through a concrete type, as shown below:
2802 fn get_bar_good() -> f64 {
2803 <MyStruct as Foo>::BAR
2810 An attempt was made to implement `Drop` on a concrete specialization of a
2811 generic type. An example is shown below:
2813 ```compile_fail,E0366
2818 impl Drop for Foo<u32> {
2819 fn drop(&mut self) {}
2823 This code is not legal: it is not possible to specialize `Drop` to a subset of
2824 implementations of a generic type. One workaround for this is to wrap the
2825 generic type, as shown below:
2837 fn drop(&mut self) {}
2843 An attempt was made to implement `Drop` on a specialization of a generic type.
2844 An example is shown below:
2846 ```compile_fail,E0367
2849 struct MyStruct<T> {
2853 impl<T: Foo> Drop for MyStruct<T> {
2854 fn drop(&mut self) {}
2858 This code is not legal: it is not possible to specialize `Drop` to a subset of
2859 implementations of a generic type. In order for this code to work, `MyStruct`
2860 must also require that `T` implements `Foo`. Alternatively, another option is
2861 to wrap the generic type in another that specializes appropriately:
2866 struct MyStruct<T> {
2870 struct MyStructWrapper<T: Foo> {
2874 impl <T: Foo> Drop for MyStructWrapper<T> {
2875 fn drop(&mut self) {}
2881 This error indicates that a binary assignment operator like `+=` or `^=` was
2882 applied to a type that doesn't support it. For example:
2884 ```compile_fail,E0368
2885 let mut x = 12f32; // error: binary operation `<<` cannot be applied to
2891 To fix this error, please check that this type implements this binary
2895 let mut x = 12u32; // the `u32` type does implement the `ShlAssign` trait
2900 It is also possible to overload most operators for your own type by
2901 implementing the `[OP]Assign` traits from `std::ops`.
2903 Another problem you might be facing is this: suppose you've overloaded the `+`
2904 operator for some type `Foo` by implementing the `std::ops::Add` trait for
2905 `Foo`, but you find that using `+=` does not work, as in this example:
2907 ```compile_fail,E0368
2915 fn add(self, rhs: Foo) -> Foo {
2921 let mut x: Foo = Foo(5);
2922 x += Foo(7); // error, `+= cannot be applied to the type `Foo`
2926 This is because `AddAssign` is not automatically implemented, so you need to
2927 manually implement it for your type.
2931 A binary operation was attempted on a type which doesn't support it.
2932 Erroneous code example:
2934 ```compile_fail,E0369
2935 let x = 12f32; // error: binary operation `<<` cannot be applied to
2941 To fix this error, please check that this type implements this binary
2945 let x = 12u32; // the `u32` type does implement it:
2946 // https://doc.rust-lang.org/stable/std/ops/trait.Shl.html
2951 It is also possible to overload most operators for your own type by
2952 implementing traits from `std::ops`.
2954 String concatenation appends the string on the right to the string on the
2955 left and may require reallocation. This requires ownership of the string
2956 on the left. If something should be added to a string literal, move the
2957 literal to the heap by allocating it with `to_owned()` like in
2958 `"Your text".to_owned()`.
2963 The maximum value of an enum was reached, so it cannot be automatically
2964 set in the next enum value. Erroneous code example:
2967 #[deny(overflowing_literals)]
2969 X = 0x7fffffffffffffff,
2970 Y, // error: enum discriminant overflowed on value after
2971 // 9223372036854775807: i64; set explicitly via
2972 // Y = -9223372036854775808 if that is desired outcome
2976 To fix this, please set manually the next enum value or put the enum variant
2977 with the maximum value at the end of the enum. Examples:
2981 X = 0x7fffffffffffffff,
2991 X = 0x7fffffffffffffff,
2997 When `Trait2` is a subtrait of `Trait1` (for example, when `Trait2` has a
2998 definition like `trait Trait2: Trait1 { ... }`), it is not allowed to implement
2999 `Trait1` for `Trait2`. This is because `Trait2` already implements `Trait1` by
3000 definition, so it is not useful to do this.
3004 ```compile_fail,E0371
3005 trait Foo { fn foo(&self) { } }
3009 impl Bar for Baz { } // error, `Baz` implements `Bar` by definition
3010 impl Foo for Baz { } // error, `Baz` implements `Bar` which implements `Foo`
3011 impl Baz for Baz { } // error, `Baz` (trivially) implements `Baz`
3012 impl Baz for Bar { } // Note: This is OK
3017 A struct without a field containing an unsized type cannot implement
3019 [unsized type](https://doc.rust-lang.org/book/first-edition/unsized-types.html)
3020 is any type that the compiler doesn't know the length or alignment of at
3021 compile time. Any struct containing an unsized type is also unsized.
3023 Example of erroneous code:
3025 ```compile_fail,E0374
3026 #![feature(coerce_unsized)]
3027 use std::ops::CoerceUnsized;
3029 struct Foo<T: ?Sized> {
3033 // error: Struct `Foo` has no unsized fields that need `CoerceUnsized`.
3034 impl<T, U> CoerceUnsized<Foo<U>> for Foo<T>
3035 where T: CoerceUnsized<U> {}
3038 `CoerceUnsized` is used to coerce one struct containing an unsized type
3039 into another struct containing a different unsized type. If the struct
3040 doesn't have any fields of unsized types then you don't need explicit
3041 coercion to get the types you want. To fix this you can either
3042 not try to implement `CoerceUnsized` or you can add a field that is
3043 unsized to the struct.
3048 #![feature(coerce_unsized)]
3049 use std::ops::CoerceUnsized;
3051 // We don't need to impl `CoerceUnsized` here.
3056 // We add the unsized type field to the struct.
3057 struct Bar<T: ?Sized> {
3062 // The struct has an unsized field so we can implement
3063 // `CoerceUnsized` for it.
3064 impl<T, U> CoerceUnsized<Bar<U>> for Bar<T>
3065 where T: CoerceUnsized<U> {}
3068 Note that `CoerceUnsized` is mainly used by smart pointers like `Box`, `Rc`
3069 and `Arc` to be able to mark that they can coerce unsized types that they
3074 A struct with more than one field containing an unsized type cannot implement
3075 `CoerceUnsized`. This only occurs when you are trying to coerce one of the
3076 types in your struct to another type in the struct. In this case we try to
3077 impl `CoerceUnsized` from `T` to `U` which are both types that the struct
3078 takes. An [unsized type] is any type that the compiler doesn't know the length
3079 or alignment of at compile time. Any struct containing an unsized type is also
3082 Example of erroneous code:
3084 ```compile_fail,E0375
3085 #![feature(coerce_unsized)]
3086 use std::ops::CoerceUnsized;
3088 struct Foo<T: ?Sized, U: ?Sized> {
3094 // error: Struct `Foo` has more than one unsized field.
3095 impl<T, U> CoerceUnsized<Foo<U, T>> for Foo<T, U> {}
3098 `CoerceUnsized` only allows for coercion from a structure with a single
3099 unsized type field to another struct with a single unsized type field.
3100 In fact Rust only allows for a struct to have one unsized type in a struct
3101 and that unsized type must be the last field in the struct. So having two
3102 unsized types in a single struct is not allowed by the compiler. To fix this
3103 use only one field containing an unsized type in the struct and then use
3104 multiple structs to manage each unsized type field you need.
3109 #![feature(coerce_unsized)]
3110 use std::ops::CoerceUnsized;
3112 struct Foo<T: ?Sized> {
3117 impl <T, U> CoerceUnsized<Foo<U>> for Foo<T>
3118 where T: CoerceUnsized<U> {}
3120 fn coerce_foo<T: CoerceUnsized<U>, U>(t: T) -> Foo<U> {
3121 Foo { a: 12i32, b: t } // we use coercion to get the `Foo<U>` type we need
3125 [unsized type]: https://doc.rust-lang.org/book/first-edition/unsized-types.html
3129 The type you are trying to impl `CoerceUnsized` for is not a struct.
3130 `CoerceUnsized` can only be implemented for a struct. Unsized types are
3131 already able to be coerced without an implementation of `CoerceUnsized`
3132 whereas a struct containing an unsized type needs to know the unsized type
3133 field it's containing is able to be coerced. An
3134 [unsized type](https://doc.rust-lang.org/book/first-edition/unsized-types.html)
3135 is any type that the compiler doesn't know the length or alignment of at
3136 compile time. Any struct containing an unsized type is also unsized.
3138 Example of erroneous code:
3140 ```compile_fail,E0376
3141 #![feature(coerce_unsized)]
3142 use std::ops::CoerceUnsized;
3144 struct Foo<T: ?Sized> {
3148 // error: The type `U` is not a struct
3149 impl<T, U> CoerceUnsized<U> for Foo<T> {}
3152 The `CoerceUnsized` trait takes a struct type. Make sure the type you are
3153 providing to `CoerceUnsized` is a struct with only the last field containing an
3159 #![feature(coerce_unsized)]
3160 use std::ops::CoerceUnsized;
3166 // The `Foo<U>` is a struct so `CoerceUnsized` can be implemented
3167 impl<T, U> CoerceUnsized<Foo<U>> for Foo<T> where T: CoerceUnsized<U> {}
3170 Note that in Rust, structs can only contain an unsized type if the field
3171 containing the unsized type is the last and only unsized type field in the
3176 Default impls are only allowed for traits with no methods or associated items.
3177 For more information see the [opt-in builtin traits RFC][RFC 19].
3179 [RFC 19]: https://github.com/rust-lang/rfcs/blob/master/text/0019-opt-in-builtin-traits.md
3183 You tried to implement methods for a primitive type. Erroneous code example:
3185 ```compile_fail,E0390
3191 // error: only a single inherent implementation marked with
3192 // `#[lang = "mut_ptr"]` is allowed for the `*mut T` primitive
3195 This isn't allowed, but using a trait to implement a method is a good solution.
3207 impl Bar for *mut Foo {
3214 This error indicates that a type or lifetime parameter has been declared
3215 but not actually used. Here is an example that demonstrates the error:
3217 ```compile_fail,E0392
3223 If the type parameter was included by mistake, this error can be fixed
3224 by simply removing the type parameter, as shown below:
3232 Alternatively, if the type parameter was intentionally inserted, it must be
3233 used. A simple fix is shown below:
3241 This error may also commonly be found when working with unsafe code. For
3242 example, when using raw pointers one may wish to specify the lifetime for
3243 which the pointed-at data is valid. An initial attempt (below) causes this
3246 ```compile_fail,E0392
3252 We want to express the constraint that Foo should not outlive `'a`, because
3253 the data pointed to by `T` is only valid for that lifetime. The problem is
3254 that there are no actual uses of `'a`. It's possible to work around this
3255 by adding a PhantomData type to the struct, using it to tell the compiler
3256 to act as if the struct contained a borrowed reference `&'a T`:
3259 use std::marker::PhantomData;
3261 struct Foo<'a, T: 'a> {
3263 phantom: PhantomData<&'a T>
3267 [PhantomData] can also be used to express information about unused type
3270 [PhantomData]: https://doc.rust-lang.org/std/marker/struct.PhantomData.html
3274 A type parameter which references `Self` in its default value was not specified.
3275 Example of erroneous code:
3277 ```compile_fail,E0393
3280 fn together_we_will_rule_the_galaxy(son: &A) {}
3281 // error: the type parameter `T` must be explicitly specified in an
3282 // object type because its default value `Self` references the
3286 A trait object is defined over a single, fully-defined trait. With a regular
3287 default parameter, this parameter can just be substituted in. However, if the
3288 default parameter is `Self`, the trait changes for each concrete type; i.e.
3289 `i32` will be expected to implement `A<i32>`, `bool` will be expected to
3290 implement `A<bool>`, etc... These types will not share an implementation of a
3291 fully-defined trait; instead they share implementations of a trait with
3292 different parameters substituted in for each implementation. This is
3293 irreconcilable with what we need to make a trait object work, and is thus
3294 disallowed. Making the trait concrete by explicitly specifying the value of the
3295 defaulted parameter will fix this issue. Fixed example:
3300 fn together_we_will_rule_the_galaxy(son: &A<i32>) {} // Ok!
3305 You implemented a trait, overriding one or more of its associated types but did
3306 not reimplement its default methods.
3308 Example of erroneous code:
3310 ```compile_fail,E0399
3311 #![feature(associated_type_defaults)]
3319 // error - the following trait items need to be reimplemented as
3320 // `Assoc` was overridden: `bar`
3325 To fix this, add an implementation for each default method from the trait:
3328 #![feature(associated_type_defaults)]
3337 fn bar(&self) {} // ok!
3343 The functional record update syntax is only allowed for structs. (Struct-like
3344 enum variants don't qualify, for example.)
3346 Erroneous code example:
3348 ```compile_fail,E0436
3349 enum PublicationFrequency {
3351 SemiMonthly { days: (u8, u8), annual_special: bool },
3354 fn one_up_competitor(competitor_frequency: PublicationFrequency)
3355 -> PublicationFrequency {
3356 match competitor_frequency {
3357 PublicationFrequency::Weekly => PublicationFrequency::SemiMonthly {
3358 days: (1, 15), annual_special: false
3360 c @ PublicationFrequency::SemiMonthly{ .. } =>
3361 PublicationFrequency::SemiMonthly {
3362 annual_special: true, ..c // error: functional record update
3363 // syntax requires a struct
3369 Rewrite the expression without functional record update syntax:
3372 enum PublicationFrequency {
3374 SemiMonthly { days: (u8, u8), annual_special: bool },
3377 fn one_up_competitor(competitor_frequency: PublicationFrequency)
3378 -> PublicationFrequency {
3379 match competitor_frequency {
3380 PublicationFrequency::Weekly => PublicationFrequency::SemiMonthly {
3381 days: (1, 15), annual_special: false
3383 PublicationFrequency::SemiMonthly{ days, .. } =>
3384 PublicationFrequency::SemiMonthly {
3385 days, annual_special: true // ok!
3393 The length of the platform-intrinsic function `simd_shuffle`
3394 wasn't specified. Erroneous code example:
3396 ```compile_fail,E0439
3397 #![feature(platform_intrinsics)]
3399 extern "platform-intrinsic" {
3400 fn simd_shuffle<A,B>(a: A, b: A, c: [u32; 8]) -> B;
3401 // error: invalid `simd_shuffle`, needs length: `simd_shuffle`
3405 The `simd_shuffle` function needs the length of the array passed as
3406 last parameter in its name. Example:
3409 #![feature(platform_intrinsics)]
3411 extern "platform-intrinsic" {
3412 fn simd_shuffle8<A,B>(a: A, b: A, c: [u32; 8]) -> B;
3418 A platform-specific intrinsic function has the wrong number of type
3419 parameters. Erroneous code example:
3421 ```compile_fail,E0440
3422 #![feature(repr_simd)]
3423 #![feature(platform_intrinsics)]
3426 struct f64x2(f64, f64);
3428 extern "platform-intrinsic" {
3429 fn x86_mm_movemask_pd<T>(x: f64x2) -> i32;
3430 // error: platform-specific intrinsic has wrong number of type
3435 Please refer to the function declaration to see if it corresponds
3436 with yours. Example:
3439 #![feature(repr_simd)]
3440 #![feature(platform_intrinsics)]
3443 struct f64x2(f64, f64);
3445 extern "platform-intrinsic" {
3446 fn x86_mm_movemask_pd(x: f64x2) -> i32;
3452 An unknown platform-specific intrinsic function was used. Erroneous
3455 ```compile_fail,E0441
3456 #![feature(repr_simd)]
3457 #![feature(platform_intrinsics)]
3460 struct i16x8(i16, i16, i16, i16, i16, i16, i16, i16);
3462 extern "platform-intrinsic" {
3463 fn x86_mm_adds_ep16(x: i16x8, y: i16x8) -> i16x8;
3464 // error: unrecognized platform-specific intrinsic function
3468 Please verify that the function name wasn't misspelled, and ensure
3469 that it is declared in the rust source code (in the file
3470 src/librustc_platform_intrinsics/x86.rs). Example:
3473 #![feature(repr_simd)]
3474 #![feature(platform_intrinsics)]
3477 struct i16x8(i16, i16, i16, i16, i16, i16, i16, i16);
3479 extern "platform-intrinsic" {
3480 fn x86_mm_adds_epi16(x: i16x8, y: i16x8) -> i16x8; // ok!
3486 Intrinsic argument(s) and/or return value have the wrong type.
3487 Erroneous code example:
3489 ```compile_fail,E0442
3490 #![feature(repr_simd)]
3491 #![feature(platform_intrinsics)]
3494 struct i8x16(i8, i8, i8, i8, i8, i8, i8, i8,
3495 i8, i8, i8, i8, i8, i8, i8, i8);
3497 struct i32x4(i32, i32, i32, i32);
3499 struct i64x2(i64, i64);
3501 extern "platform-intrinsic" {
3502 fn x86_mm_adds_epi16(x: i8x16, y: i32x4) -> i64x2;
3503 // error: intrinsic arguments/return value have wrong type
3507 To fix this error, please refer to the function declaration to give
3508 it the awaited types. Example:
3511 #![feature(repr_simd)]
3512 #![feature(platform_intrinsics)]
3515 struct i16x8(i16, i16, i16, i16, i16, i16, i16, i16);
3517 extern "platform-intrinsic" {
3518 fn x86_mm_adds_epi16(x: i16x8, y: i16x8) -> i16x8; // ok!
3524 Intrinsic argument(s) and/or return value have the wrong type.
3525 Erroneous code example:
3527 ```compile_fail,E0443
3528 #![feature(repr_simd)]
3529 #![feature(platform_intrinsics)]
3532 struct i16x8(i16, i16, i16, i16, i16, i16, i16, i16);
3534 struct i64x8(i64, i64, i64, i64, i64, i64, i64, i64);
3536 extern "platform-intrinsic" {
3537 fn x86_mm_adds_epi16(x: i16x8, y: i16x8) -> i64x8;
3538 // error: intrinsic argument/return value has wrong type
3542 To fix this error, please refer to the function declaration to give
3543 it the awaited types. Example:
3546 #![feature(repr_simd)]
3547 #![feature(platform_intrinsics)]
3550 struct i16x8(i16, i16, i16, i16, i16, i16, i16, i16);
3552 extern "platform-intrinsic" {
3553 fn x86_mm_adds_epi16(x: i16x8, y: i16x8) -> i16x8; // ok!
3559 A platform-specific intrinsic function has wrong number of arguments.
3560 Erroneous code example:
3562 ```compile_fail,E0444
3563 #![feature(repr_simd)]
3564 #![feature(platform_intrinsics)]
3567 struct f64x2(f64, f64);
3569 extern "platform-intrinsic" {
3570 fn x86_mm_movemask_pd(x: f64x2, y: f64x2, z: f64x2) -> i32;
3571 // error: platform-specific intrinsic has invalid number of arguments
3575 Please refer to the function declaration to see if it corresponds
3576 with yours. Example:
3579 #![feature(repr_simd)]
3580 #![feature(platform_intrinsics)]
3583 struct f64x2(f64, f64);
3585 extern "platform-intrinsic" {
3586 fn x86_mm_movemask_pd(x: f64x2) -> i32; // ok!
3592 The `typeof` keyword is currently reserved but unimplemented.
3593 Erroneous code example:
3595 ```compile_fail,E0516
3597 let x: typeof(92) = 92;
3601 Try using type inference instead. Example:
3611 A non-default implementation was already made on this type so it cannot be
3612 specialized further. Erroneous code example:
3614 ```compile_fail,E0520
3615 #![feature(specialization)]
3622 impl<T> SpaceLlama for T {
3623 default fn fly(&self) {}
3627 // applies to all `Clone` T and overrides the previous impl
3628 impl<T: Clone> SpaceLlama for T {
3632 // since `i32` is clone, this conflicts with the previous implementation
3633 impl SpaceLlama for i32 {
3634 default fn fly(&self) {}
3635 // error: item `fly` is provided by an `impl` that specializes
3636 // another, but the item in the parent `impl` is not marked
3637 // `default` and so it cannot be specialized.
3641 Specialization only allows you to override `default` functions in
3644 To fix this error, you need to mark all the parent implementations as default.
3648 #![feature(specialization)]
3655 impl<T> SpaceLlama for T {
3656 default fn fly(&self) {} // This is a parent implementation.
3659 // applies to all `Clone` T; overrides the previous impl
3660 impl<T: Clone> SpaceLlama for T {
3661 default fn fly(&self) {} // This is a parent implementation but was
3662 // previously not a default one, causing the error
3665 // applies to i32, overrides the previous two impls
3666 impl SpaceLlama for i32 {
3667 fn fly(&self) {} // And now that's ok!
3673 The number of elements in an array or slice pattern differed from the number of
3674 elements in the array being matched.
3676 Example of erroneous code:
3678 ```compile_fail,E0527
3679 #![feature(slice_patterns)]
3681 let r = &[1, 2, 3, 4];
3683 &[a, b] => { // error: pattern requires 2 elements but array
3685 println!("a={}, b={}", a, b);
3690 Ensure that the pattern is consistent with the size of the matched
3691 array. Additional elements can be matched with `..`:
3694 #![feature(slice_patterns)]
3696 let r = &[1, 2, 3, 4];
3698 &[a, b, ..] => { // ok!
3699 println!("a={}, b={}", a, b);
3706 An array or slice pattern required more elements than were present in the
3709 Example of erroneous code:
3711 ```compile_fail,E0528
3712 #![feature(slice_patterns)]
3716 &[a, b, c, rest..] => { // error: pattern requires at least 3
3717 // elements but array has 2
3718 println!("a={}, b={}, c={} rest={:?}", a, b, c, rest);
3723 Ensure that the matched array has at least as many elements as the pattern
3724 requires. You can match an arbitrary number of remaining elements with `..`:
3727 #![feature(slice_patterns)]
3729 let r = &[1, 2, 3, 4, 5];
3731 &[a, b, c, rest..] => { // ok!
3732 // prints `a=1, b=2, c=3 rest=[4, 5]`
3733 println!("a={}, b={}, c={} rest={:?}", a, b, c, rest);
3740 An array or slice pattern was matched against some other type.
3742 Example of erroneous code:
3744 ```compile_fail,E0529
3745 #![feature(slice_patterns)]
3749 [a, b] => { // error: expected an array or slice, found `f32`
3750 println!("a={}, b={}", a, b);
3755 Ensure that the pattern and the expression being matched on are of consistent
3759 #![feature(slice_patterns)]
3764 println!("a={}, b={}", a, b);
3771 An unknown field was specified into an enum's structure variant.
3773 Erroneous code example:
3775 ```compile_fail,E0559
3780 let s = Field::Fool { joke: 0 };
3781 // error: struct variant `Field::Fool` has no field named `joke`
3784 Verify you didn't misspell the field's name or that the field exists. Example:
3791 let s = Field::Fool { joke: 0 }; // ok!
3796 An unknown field was specified into a structure.
3798 Erroneous code example:
3800 ```compile_fail,E0560
3805 let s = Simba { mother: 1, father: 0 };
3806 // error: structure `Simba` has no field named `father`
3809 Verify you didn't misspell the field's name or that the field exists. Example:
3817 let s = Simba { mother: 1, father: 0 }; // ok!
3822 Abstract return types (written `impl Trait` for some trait `Trait`) are only
3823 allowed as function return types.
3825 Erroneous code example:
3827 ```compile_fail,E0562
3828 #![feature(conservative_impl_trait)]
3831 let count_to_ten: impl Iterator<Item=usize> = 0..10;
3832 // error: `impl Trait` not allowed outside of function and inherent method
3834 for i in count_to_ten {
3840 Make sure `impl Trait` only appears in return-type position.
3843 #![feature(conservative_impl_trait)]
3845 fn count_to_n(n: usize) -> impl Iterator<Item=usize> {
3850 for i in count_to_n(10) { // ok!
3856 See [RFC 1522] for more details.
3858 [RFC 1522]: https://github.com/rust-lang/rfcs/blob/master/text/1522-conservative-impl-trait.md
3862 If an impl has a generic parameter with the `#[may_dangle]` attribute, then
3863 that impl must be declared as an `unsafe impl.
3865 Erroneous code example:
3867 ```compile_fail,E0569
3868 #![feature(generic_param_attrs)]
3869 #![feature(dropck_eyepatch)]
3872 impl<#[may_dangle] X> Drop for Foo<X> {
3873 fn drop(&mut self) { }
3877 In this example, we are asserting that the destructor for `Foo` will not
3878 access any data of type `X`, and require this assertion to be true for
3879 overall safety in our program. The compiler does not currently attempt to
3880 verify this assertion; therefore we must tag this `impl` as unsafe.
3884 The requested ABI is unsupported by the current target.
3886 The rust compiler maintains for each target a blacklist of ABIs unsupported on
3887 that target. If an ABI is present in such a list this usually means that the
3888 target / ABI combination is currently unsupported by llvm.
3890 If necessary, you can circumvent this check using custom target specifications.
3894 A return statement was found outside of a function body.
3896 Erroneous code example:
3898 ```compile_fail,E0572
3899 const FOO: u32 = return 0; // error: return statement outside of function body
3904 To fix this issue, just remove the return keyword or move the expression into a
3910 fn some_fn() -> u32 {
3921 In a `fn` type, a lifetime appears only in the return type,
3922 and not in the arguments types.
3924 Erroneous code example:
3926 ```compile_fail,E0581
3928 // Here, `'a` appears only in the return type:
3929 let x: for<'a> fn() -> &'a i32;
3933 To fix this issue, either use the lifetime in the arguments, or use
3938 // Here, `'a` appears only in the return type:
3939 let x: for<'a> fn(&'a i32) -> &'a i32;
3940 let y: fn() -> &'static i32;
3944 Note: The examples above used to be (erroneously) accepted by the
3945 compiler, but this was since corrected. See [issue #33685] for more
3948 [issue #33685]: https://github.com/rust-lang/rust/issues/33685
3952 A lifetime appears only in an associated-type binding,
3953 and not in the input types to the trait.
3955 Erroneous code example:
3957 ```compile_fail,E0582
3959 // No type can satisfy this requirement, since `'a` does not
3960 // appear in any of the input types (here, `i32`):
3961 where F: for<'a> Fn(i32) -> Option<&'a i32>
3968 To fix this issue, either use the lifetime in the inputs, or use
3972 fn bar<F, G>(t: F, u: G)
3973 where F: for<'a> Fn(&'a i32) -> Option<&'a i32>,
3974 G: Fn(i32) -> Option<&'static i32>,
3981 Note: The examples above used to be (erroneously) accepted by the
3982 compiler, but this was since corrected. See [issue #33685] for more
3985 [issue #33685]: https://github.com/rust-lang/rust/issues/33685
3989 ```compile_fail,E0599
3993 x.chocolate(); // error: no method named `chocolate` found for type `Mouth`
3994 // in the current scope
3999 An unary operator was used on a type which doesn't implement it.
4001 Example of erroneous code:
4003 ```compile_fail,E0600
4009 !Question::Yes; // error: cannot apply unary operator `!` to type `Question`
4012 In this case, `Question` would need to implement the `std::ops::Not` trait in
4013 order to be able to use `!` on it. Let's implement it:
4023 // We implement the `Not` trait on the enum.
4024 impl Not for Question {
4027 fn not(self) -> bool {
4029 Question::Yes => false, // If the `Answer` is `Yes`, then it
4031 Question::No => true, // And here we do the opposite.
4036 assert_eq!(!Question::Yes, false);
4037 assert_eq!(!Question::No, true);
4042 An attempt to index into a type which doesn't implement the `std::ops::Index`
4043 trait was performed.
4045 Erroneous code example:
4047 ```compile_fail,E0608
4048 0u8[2]; // error: cannot index into a value of type `u8`
4051 To be able to index into a type it needs to implement the `std::ops::Index`
4055 let v: Vec<u8> = vec![0, 1, 2, 3];
4057 // The `Vec` type implements the `Index` trait so you can do:
4058 println!("{}", v[2]);
4063 A cast to `char` was attempted on a type other than `u8`.
4065 Erroneous code example:
4067 ```compile_fail,E0604
4068 0u32 as char; // error: only `u8` can be cast as `char`, not `u32`
4071 As the error message indicates, only `u8` can be cast into `char`. Example:
4074 let c = 86u8 as char; // ok!
4078 For more information about casts, take a look at The Book:
4079 https://doc.rust-lang.org/book/first-edition/casting-between-types.html
4083 An invalid cast was attempted.
4085 Erroneous code examples:
4087 ```compile_fail,E0605
4089 x as Vec<u8>; // error: non-primitive cast: `u8` as `std::vec::Vec<u8>`
4093 let v = 0 as *const u8; // So here, `v` is a `*const u8`.
4094 v as &u8; // error: non-primitive cast: `*const u8` as `&u8`
4097 Only primitive types can be cast into each other. Examples:
4103 let v = 0 as *const u8;
4104 v as *const i8; // ok!
4107 For more information about casts, take a look at The Book:
4108 https://doc.rust-lang.org/book/first-edition/casting-between-types.html
4112 An incompatible cast was attempted.
4114 Erroneous code example:
4116 ```compile_fail,E0606
4117 let x = &0u8; // Here, `x` is a `&u8`.
4118 let y: u32 = x as u32; // error: casting `&u8` as `u32` is invalid
4121 When casting, keep in mind that only primitive types can be cast into each
4126 let y: u32 = *x as u32; // We dereference it first and then cast it.
4129 For more information about casts, take a look at The Book:
4130 https://doc.rust-lang.org/book/first-edition/casting-between-types.html
4134 A cast between a thin and a fat pointer was attempted.
4136 Erroneous code example:
4138 ```compile_fail,E0607
4139 let v = 0 as *const u8;
4143 First: what are thin and fat pointers?
4145 Thin pointers are "simple" pointers: they are purely a reference to a memory
4148 Fat pointers are pointers referencing Dynamically Sized Types (also called DST).
4149 DST don't have a statically known size, therefore they can only exist behind
4150 some kind of pointers that contain additional information. Slices and trait
4151 objects are DSTs. In the case of slices, the additional information the fat
4152 pointer holds is their size.
4154 To fix this error, don't try to cast directly between thin and fat pointers.
4156 For more information about casts, take a look at The Book:
4157 https://doc.rust-lang.org/book/first-edition/casting-between-types.html
4161 Attempted to access a non-existent field in a struct.
4163 Erroneous code example:
4165 ```compile_fail,E0609
4166 struct StructWithFields {
4170 let s = StructWithFields { x: 0 };
4171 println!("{}", s.foo); // error: no field `foo` on type `StructWithFields`
4174 To fix this error, check that you didn't misspell the field's name or that the
4175 field actually exists. Example:
4178 struct StructWithFields {
4182 let s = StructWithFields { x: 0 };
4183 println!("{}", s.x); // ok!
4188 Attempted to access a field on a primitive type.
4190 Erroneous code example:
4192 ```compile_fail,E0610
4194 println!("{}", x.foo); // error: `{integer}` is a primitive type, therefore
4195 // doesn't have fields
4198 Primitive types are the most basic types available in Rust and don't have
4199 fields. To access data via named fields, struct types are used. Example:
4202 // We declare struct called `Foo` containing two fields:
4208 // We create an instance of this struct:
4209 let variable = Foo { x: 0, y: -12 };
4210 // And we can now access its fields:
4211 println!("x: {}, y: {}", variable.x, variable.y);
4214 For more information about primitives and structs, take a look at The Book:
4215 https://doc.rust-lang.org/book/first-edition/primitive-types.html
4216 https://doc.rust-lang.org/book/first-edition/structs.html
4220 Attempted to access a private field on a tuple-struct.
4222 Erroneous code example:
4224 ```compile_fail,E0611
4226 pub struct Foo(u32);
4229 pub fn new() -> Foo { Foo(0) }
4233 let y = some_module::Foo::new();
4234 println!("{}", y.0); // error: field `0` of tuple-struct `some_module::Foo`
4238 Since the field is private, you have two solutions:
4240 1) Make the field public:
4244 pub struct Foo(pub u32); // The field is now public.
4247 pub fn new() -> Foo { Foo(0) }
4251 let y = some_module::Foo::new();
4252 println!("{}", y.0); // So we can access it directly.
4255 2) Add a getter function to keep the field private but allow for accessing its
4260 pub struct Foo(u32);
4263 pub fn new() -> Foo { Foo(0) }
4265 // We add the getter function.
4266 pub fn get(&self) -> &u32 { &self.0 }
4270 let y = some_module::Foo::new();
4271 println!("{}", y.get()); // So we can get the value through the function.
4276 Attempted out-of-bounds tuple index.
4278 Erroneous code example:
4280 ```compile_fail,E0612
4284 println!("{}", y.1); // error: attempted out-of-bounds tuple index `1`
4288 If a tuple/tuple-struct type has n fields, you can only try to access these n
4289 fields from 0 to (n - 1). So in this case, you can only index `0`. Example:
4295 println!("{}", y.0); // ok!
4300 Attempted to dereference a variable which cannot be dereferenced.
4302 Erroneous code example:
4304 ```compile_fail,E0614
4306 *y; // error: type `u32` cannot be dereferenced
4309 Only types implementing `std::ops::Deref` can be dereferenced (such as `&T`).
4315 // So here, `x` is a `&u32`, so we can dereference it:
4321 Attempted to access a method like a field.
4323 Erroneous code example:
4325 ```compile_fail,E0615
4334 let f = Foo { x: 0 };
4335 f.method; // error: attempted to take value of method `method` on type `Foo`
4338 If you want to use a method, add `()` after it:
4341 # struct Foo { x: u32 }
4342 # impl Foo { fn method(&self) {} }
4343 # let f = Foo { x: 0 };
4347 However, if you wanted to access a field of a struct check that the field name
4348 is spelled correctly. Example:
4351 # struct Foo { x: u32 }
4352 # impl Foo { fn method(&self) {} }
4353 # let f = Foo { x: 0 };
4354 println!("{}", f.x);
4359 Attempted to access a private field on a struct.
4361 Erroneous code example:
4363 ```compile_fail,E0616
4366 x: u32, // So `x` is private in here.
4370 pub fn new() -> Foo { Foo { x: 0 } }
4374 let f = some_module::Foo::new();
4375 println!("{}", f.x); // error: field `x` of struct `some_module::Foo` is private
4378 If you want to access this field, you have two options:
4380 1) Set the field public:
4385 pub x: u32, // `x` is now public.
4389 pub fn new() -> Foo { Foo { x: 0 } }
4393 let f = some_module::Foo::new();
4394 println!("{}", f.x); // ok!
4397 2) Add a getter function:
4402 x: u32, // So `x` is still private in here.
4406 pub fn new() -> Foo { Foo { x: 0 } }
4408 // We create the getter function here:
4409 pub fn get_x(&self) -> &u32 { &self.x }
4413 let f = some_module::Foo::new();
4414 println!("{}", f.get_x()); // ok!
4419 Attempted to pass an invalid type of variable into a variadic function.
4421 Erroneous code example:
4423 ```compile_fail,E0617
4425 fn printf(c: *const i8, ...);
4429 printf(::std::ptr::null(), 0f32);
4430 // error: can't pass an `f32` to variadic function, cast to `c_double`
4434 Certain Rust types must be cast before passing them to a variadic function,
4435 because of arcane ABI rules dictated by the C standard. To fix the error,
4436 cast the value to the type specified by the error message (which you may need
4437 to import from `std::os::raw`).
4441 Attempted to call something which isn't a function nor a method.
4443 Erroneous code examples:
4445 ```compile_fail,E0618
4450 X::Entry(); // error: expected function, found `X::Entry`
4454 x(); // error: expected function, found `i32`
4457 Only functions and methods can be called using `()`. Example:
4460 // We declare a function:
4461 fn i_am_a_function() {}
4469 The type-checker needed to know the type of an expression, but that type had not
4472 Erroneous code example:
4474 ```compile_fail,E0619
4478 // Here, the type of `v` is not (yet) known, so we
4479 // cannot resolve this method call:
4480 v.to_uppercase(); // error: the type of this value must be known in
4487 Type inference typically proceeds from the top of the function to the bottom,
4488 figuring out types as it goes. In some cases -- notably method calls and
4489 overloadable operators like `*` -- the type checker may not have enough
4490 information *yet* to make progress. This can be true even if the rest of the
4491 function provides enough context (because the type-checker hasn't looked that
4492 far ahead yet). In this case, type annotations can be used to help it along.
4494 To fix this error, just specify the type of the variable. Example:
4497 let mut x: Vec<String> = vec![]; // We precise the type of the vec elements.
4500 v.to_uppercase(); // Since rustc now knows the type of the vec elements,
4501 // we can use `v`'s methods.
4509 A cast to an unsized type was attempted.
4511 Erroneous code example:
4513 ```compile_fail,E0620
4514 let x = &[1_usize, 2] as [usize]; // error: cast to unsized type: `&[usize; 2]`
4518 In Rust, some types don't have a known size at compile-time. For example, in a
4519 slice type like `[u32]`, the number of elements is not known at compile-time and
4520 hence the overall size cannot be computed. As a result, such types can only be
4521 manipulated through a reference (e.g., `&T` or `&mut T`) or other pointer-type
4522 (e.g., `Box` or `Rc`). Try casting to a reference instead:
4525 let x = &[1_usize, 2] as &[usize]; // ok!
4530 An intrinsic was declared without being a function.
4532 Erroneous code example:
4534 ```compile_fail,E0622
4535 #![feature(intrinsics)]
4536 extern "rust-intrinsic" {
4537 pub static breakpoint : unsafe extern "rust-intrinsic" fn();
4538 // error: intrinsic must be a function
4541 fn main() { unsafe { breakpoint(); } }
4544 An intrinsic is a function available for use in a given programming language
4545 whose implementation is handled specially by the compiler. In order to fix this
4546 error, just declare a function.
4550 A private item was used outside of its scope.
4552 Erroneous code example:
4554 ```compile_fail,E0624
4563 let foo = inner::Foo;
4564 foo.method(); // error: method `method` is private
4567 Two possibilities are available to solve this issue:
4569 1. Only use the item in the scope it has been defined:
4579 pub fn call_method(foo: &Foo) { // We create a public function.
4580 foo.method(); // Which calls the item.
4584 let foo = inner::Foo;
4585 inner::call_method(&foo); // And since the function is public, we can call the
4586 // method through it.
4589 2. Make the item public:
4596 pub fn method(&self) {} // It's now public.
4600 let foo = inner::Foo;
4601 foo.method(); // Ok!
4607 register_diagnostics! {
4608 // E0035, merged into E0087/E0089
4609 // E0036, merged into E0087/E0089
4619 // E0159, // use of trait `{}` as struct constructor
4620 // E0163, // merged into E0071
4623 // E0172, // non-trait found in a type sum, moved to resolve
4624 // E0173, // manual implementations of unboxed closure traits are experimental
4626 // E0182, // merged into E0229
4628 // E0187, // can't infer the kind of the closure
4629 // E0188, // can not cast an immutable reference to a mutable pointer
4630 // E0189, // deprecated: can only cast a boxed pointer to a boxed object
4631 // E0190, // deprecated: can only cast a &-pointer to an &-object
4632 // E0196, // cannot determine a type for this closure
4633 E0203, // type parameter has more than one relaxed default bound,
4634 // and only one is supported
4636 // E0209, // builtin traits can only be implemented on structs or enums
4637 E0212, // cannot extract an associated type from a higher-ranked trait bound
4638 // E0213, // associated types are not accepted in this context
4639 // E0215, // angle-bracket notation is not stable with `Fn`
4640 // E0216, // parenthetical notation is only stable with `Fn`
4641 // E0217, // ambiguous associated type, defined in multiple supertraits
4642 // E0218, // no associated type defined
4643 // E0219, // associated type defined in higher-ranked supertrait
4644 // E0222, // Error code E0045 (variadic function must have C or cdecl calling
4645 // convention) duplicate
4646 E0224, // at least one non-builtin train is required for an object type
4647 E0227, // ambiguous lifetime bound, explicit lifetime bound required
4648 E0228, // explicit lifetime bound required
4651 // E0235, // structure constructor specifies a structure of type but
4652 // E0236, // no lang item for range syntax
4653 // E0237, // no lang item for range syntax
4654 // E0238, // parenthesized parameters may only be used with a trait
4655 // E0239, // `next` method of `Iterator` trait has unexpected type
4659 E0245, // not a trait
4660 // E0246, // invalid recursive type
4662 // E0248, // value used as a type, now reported earlier during resolution as E0412
4664 // E0319, // trait impls for defaulted traits allowed just for structs/enums
4665 // E0372, // coherence not object safe
4666 E0377, // the trait `CoerceUnsized` may only be implemented for a coercion
4667 // between structures with the same definition
4668 E0521, // redundant default implementations of trait
4669 E0533, // `{}` does not name a unit variant, unit struct or a constant
4670 // E0563, // cannot determine a type for this `impl Trait`: {} // removed in 6383de15
4671 E0564, // only named lifetimes are allowed in `impl Trait`,
4672 // but `{}` was found in the type `{}`
4673 E0567, // auto traits can not have type parameters
4674 E0568, // auto-traits can not have predicates,
4675 E0587, // struct has conflicting packed and align representation hints
4676 E0588, // packed struct cannot transitively contain a `[repr(align)]` struct
4677 E0592, // duplicate definitions with name `{}`
4678 // E0613, // Removed (merged with E0609)
4679 E0640, // infer outlives
4680 E0627, // yield statement outside of generator literal
4681 E0632, // cannot provide explicit type parameters when `impl Trait` is used in
4682 // argument position.