This error suggests that the expression arm corresponding to the noted pattern will never be reached as for all possible values of the expression being matched, one of the preceding patterns will match.
This means that perhaps some of the preceding patterns are too general, this one is too specific or the ordering is incorrect.
For example, the following match
block has too many arms:
match Some(0) {
Some(bar) => {/* ... */}
x => {/* ... */} // This handles the `None` case
_ => {/* ... */} // All possible cases have already been handled
}
Runmatch
blocks have their patterns matched in order, so, for example, putting
a wildcard arm above a more specific arm will make the latter arm irrelevant.
Ensure the ordering of the match arm is correct and remove any superfluous arms.
This error indicates that an empty match expression is invalid because the type it is matching on is non-empty (there exist values of this type). In safe code it is impossible to create an instance of an empty type, so empty match expressions are almost never desired. This error is typically fixed by adding one or more cases to the match expression.
An example of an empty type is enum Empty { }
. So, the following will work:
enum Empty {}
fn foo(x: Empty) {
match x {
// empty
}
}
RunHowever, this won’t:
fn foo(x: Option<String>) {
match x {
// empty
}
}
RunThis error indicates that the compiler cannot guarantee a matching pattern for one or more possible inputs to a match expression. Guaranteed matches are required in order to assign values to match expressions, or alternatively, determine the flow of execution.
Erroneous code example:
enum Terminator {
HastaLaVistaBaby,
TalkToMyHand,
}
let x = Terminator::HastaLaVistaBaby;
match x { // error: non-exhaustive patterns: `HastaLaVistaBaby` not covered
Terminator::TalkToMyHand => {}
}
RunIf you encounter this error you must alter your patterns so that every possible
value of the input type is matched. For types with a small number of variants
(like enums) you should probably cover all cases explicitly. Alternatively, the
underscore _
wildcard pattern can be added after all other patterns to match
“anything else”. Example:
enum Terminator {
HastaLaVistaBaby,
TalkToMyHand,
}
let x = Terminator::HastaLaVistaBaby;
match x {
Terminator::TalkToMyHand => {}
Terminator::HastaLaVistaBaby => {}
}
// or:
match x {
Terminator::TalkToMyHand => {}
_ => {}
}
RunPatterns used to bind names must be irrefutable, that is, they must guarantee that a name will be extracted in all cases.
Erroneous code example:
let x = Some(1);
let Some(y) = x;
// error: refutable pattern in local binding: `None` not covered
RunIf you encounter this error you probably need to use a match
or if let
to
deal with the possibility of failure. Example:
let x = Some(1);
match x {
Some(y) => {
// do something
},
None => {}
}
// or:
if let Some(y) = x {
// do something
}
RunThis error indicates that the bindings in a match arm would require a value to
be moved into more than one location, thus violating unique ownership. Code
like the following is invalid as it requires the entire Option<String>
to be
moved into a variable called op_string
while simultaneously requiring the
inner String
to be moved into a variable called s
.
Erroneous code example:
#![feature(bindings_after_at)]
let x = Some("s".to_string());
match x {
op_string @ Some(s) => {}, // error: use of moved value
None => {},
}
RunSee also the error E0303.
In a pattern, all values that don’t implement the Copy
trait have to be bound
the same way. The goal here is to avoid binding simultaneously by-move and
by-ref.
This limitation may be removed in a future version of Rust.
Erroneous code example:
#![feature(move_ref_pattern)]
struct X { x: (), }
let x = Some((X { x: () }, X { x: () }));
match x {
Some((y, ref z)) => {}, // error: cannot bind by-move and by-ref in the
// same pattern
None => panic!()
}
RunYou have two solutions:
Solution #1: Bind the pattern’s values the same way.
struct X { x: (), }
let x = Some((X { x: () }, X { x: () }));
match x {
Some((ref y, ref z)) => {},
// or Some((y, z)) => {}
None => panic!()
}
RunSolution #2: Implement the Copy
trait for the X
structure.
However, please keep in mind that the first solution should be preferred.
#[derive(Clone, Copy)]
struct X { x: (), }
let x = Some((X { x: () }, X { x: () }));
match x {
Some((y, ref z)) => {},
None => panic!()
}
RunThe value of statics and constants must be known at compile time, and they live for the entire lifetime of a program. Creating a boxed value allocates memory on the heap at runtime, and therefore cannot be done at compile time.
Erroneous code example:
#![feature(box_syntax)]
const CON : Box<i32> = box 0;
RunStatic and const variables can refer to other const variables. But a const variable cannot refer to a static variable.
Erroneous code example:
static X: i32 = 42;
const Y: i32 = X;
RunIn this example, Y
cannot refer to X
. To fix this, the value can be
extracted as a const and then used:
const A: i32 = 42;
static X: i32 = A;
const Y: i32 = A;
RunConstants can only be initialized by a constant value or, in a future version of Rust, a call to a const function. This error indicates the use of a path (like a::b, or x) denoting something other than one of these allowed items.
Erroneous code example:
const FOO: i32 = { let x = 0; x }; // 'x' isn't a constant nor a function!
RunTo avoid it, you have to replace the non-constant value:
const FOO: i32 = { const X : i32 = 0; X };
// or even:
const FOO2: i32 = { 0 }; // but brackets are useless here
RunA constant item was initialized with something that is not a constant expression.
Erroneous code example:
fn create_some() -> Option<u8> {
Some(1)
}
const FOO: Option<u8> = create_some(); // error!
RunThe only functions that can be called in static or constant expressions are
const
functions, and struct/enum constructors.
To fix this error, you can declare create_some
as a constant function:
const fn create_some() -> Option<u8> { // declared as a const function
Some(1)
}
const FOO: Option<u8> = create_some(); // ok!
// These are also working:
struct Bar {
x: u8,
}
const OTHER_FOO: Option<u8> = Some(1);
const BAR: Bar = Bar {x: 1};
RunA pattern attempted to extract an incorrect number of fields from a variant.
Erroneous code example:
enum Fruit {
Apple(String, String),
Pear(u32),
}
let x = Fruit::Apple(String::new(), String::new());
match x {
Fruit::Apple(a) => {}, // error!
_ => {}
}
RunA pattern used to match against an enum variant must provide a sub-pattern for each field of the enum variant.
Here the Apple
variant has two fields, and should be matched against like so:
enum Fruit {
Apple(String, String),
Pear(u32),
}
let x = Fruit::Apple(String::new(), String::new());
// Correct.
match x {
Fruit::Apple(a, b) => {},
_ => {}
}
RunMatching with the wrong number of fields has no sensible interpretation:
enum Fruit {
Apple(String, String),
Pear(u32),
}
let x = Fruit::Apple(String::new(), String::new());
// Incorrect.
match x {
Fruit::Apple(a) => {},
Fruit::Apple(a, b, c) => {},
}
RunCheck how many fields the enum was declared with and ensure that your pattern uses the same number.
Each field of a struct can only be bound once in a pattern.
Erroneous code example:
struct Foo {
a: u8,
b: u8,
}
fn main(){
let x = Foo { a:1, b:2 };
let Foo { a: x, a: y } = x;
// error: field `a` bound multiple times in the pattern
}
RunEach occurrence of a field name binds the value of that field, so to fix this error you will have to remove or alter the duplicate uses of the field name. Perhaps you misspelled another field name? Example:
struct Foo {
a: u8,
b: u8,
}
fn main(){
let x = Foo { a:1, b:2 };
let Foo { a: x, b: y } = x; // ok!
}
RunA struct pattern attempted to extract a non-existent field from a struct.
Erroneous code example:
struct Thing {
x: u32,
y: u32,
}
let thing = Thing { x: 0, y: 0 };
match thing {
Thing { x, z } => {} // error: `Thing::z` field doesn't exist
}
RunIf you are using shorthand field patterns but want to refer to the struct field
by a different name, you should rename it explicitly. Struct fields are
identified by the name used before the colon :
so struct patterns should
resemble the declaration of the struct type being matched.
struct Thing {
x: u32,
y: u32,
}
let thing = Thing { x: 0, y: 0 };
match thing {
Thing { x, y: z } => {} // we renamed `y` to `z`
}
RunA pattern for a struct fails to specify a sub-pattern for every one of the struct’s fields.
Erroneous code example:
struct Dog {
name: String,
age: u32,
}
let d = Dog { name: "Rusty".to_string(), age: 8 };
// This is incorrect.
match d {
Dog { age: x } => {}
}
RunTo fix this error, ensure that each field from the struct’s definition is
mentioned in the pattern, or use ..
to ignore unwanted fields. Example:
struct Dog {
name: String,
age: u32,
}
let d = Dog { name: "Rusty".to_string(), age: 8 };
match d {
Dog { name: ref n, age: x } => {}
}
// This is also correct (ignore unused fields).
match d {
Dog { age: x, .. } => {}
}
RunSomething other than numbers and characters has been used for a range.
Erroneous code example:
let string = "salutations !";
// The ordering relation for strings cannot be evaluated at compile time,
// so this doesn't work:
match string {
"hello" ..= "world" => {}
_ => {}
}
// This is a more general version, using a guard:
match string {
s if s >= "hello" && s <= "world" => {}
_ => {}
}
RunIn a match expression, only numbers and characters can be matched against a range. This is because the compiler checks that the range is non-empty at compile-time, and is unable to evaluate arbitrary comparison functions. If you want to capture values of an orderable type between two end-points, you can use a guard.
When matching against a range, the compiler verifies that the range is non-empty. Range patterns include both end-points, so this is equivalent to requiring the start of the range to be less than or equal to the end of the range.
Erroneous code example:
match 5u32 {
// This range is ok, albeit pointless.
1 ..= 1 => {}
// This range is empty, and the compiler can tell.
1000 ..= 5 => {}
}
RunA trait type has been dereferenced.
Erroneous code example:
let trait_obj: &SomeTrait = &"some_value";
// This tries to implicitly dereference to create an unsized local variable.
let &invalid = trait_obj;
// You can call methods without binding to the value being pointed at.
trait_obj.method_one();
trait_obj.method_two();
RunA pointer to a trait type cannot be implicitly dereferenced by a pattern. Every trait defines a type, but because the size of trait implementers isn’t fixed, this type has no compile-time size. Therefore, all accesses to trait types must be through pointers. If you encounter this error you should try to avoid dereferencing the pointer.
You can read more about trait objects in the Trait Objects section of the Reference.
The compiler doesn’t know what method to call because more than one method has the same prototype.
Erroneous code example:
struct Test;
trait Trait1 {
fn foo();
}
trait Trait2 {
fn foo();
}
impl Trait1 for Test { fn foo() {} }
impl Trait2 for Test { fn foo() {} }
fn main() {
Test::foo() // error, which foo() to call?
}
RunTo avoid this error, you have to keep only one of them and remove the others. So let’s take our example and fix it:
struct Test;
trait Trait1 {
fn foo();
}
impl Trait1 for Test { fn foo() {} }
fn main() {
Test::foo() // and now that's good!
}
RunHowever, a better solution would be using fully explicit naming of type and trait:
struct Test;
trait Trait1 {
fn foo();
}
trait Trait2 {
fn foo();
}
impl Trait1 for Test { fn foo() {} }
impl Trait2 for Test { fn foo() {} }
fn main() {
<Test as Trait1>::foo()
}
RunOne last example:
trait F {
fn m(&self);
}
trait G {
fn m(&self);
}
struct X;
impl F for X { fn m(&self) { println!("I am F"); } }
impl G for X { fn m(&self) { println!("I am G"); } }
fn main() {
let f = X;
F::m(&f); // it displays "I am F"
G::m(&f); // it displays "I am G"
}
RunTrait objects like Box<Trait>
can only be constructed when certain
requirements are satisfied by the trait in question.
Trait objects are a form of dynamic dispatch and use a dynamically sized type
for the inner type. So, for a given trait Trait
, when Trait
is treated as a
type, as in Box<Trait>
, the inner type is ‘unsized’. In such cases the boxed
pointer is a ‘fat pointer’ that contains an extra pointer to a table of methods
(among other things) for dynamic dispatch. This design mandates some
restrictions on the types of traits that are allowed to be used in trait
objects, which are collectively termed as ‘object safety’ rules.
Attempting to create a trait object for a non object-safe trait will trigger this error.
There are various rules:
Self: Sized
When Trait
is treated as a type, the type does not implement the special
Sized
trait, because the type does not have a known size at compile time and
can only be accessed behind a pointer. Thus, if we have a trait like the
following:
trait Foo where Self: Sized {
}
RunWe cannot create an object of type Box<Foo>
or &Foo
since in this case
Self
would not be Sized
.
Generally, Self: Sized
is used to indicate that the trait should not be used
as a trait object. If the trait comes from your own crate, consider removing
this restriction.
Self
type in its parameters or return typeThis happens when a trait has a method like the following:
trait Trait {
fn foo(&self) -> Self;
}
impl Trait for String {
fn foo(&self) -> Self {
"hi".to_owned()
}
}
impl Trait for u8 {
fn foo(&self) -> Self {
1
}
}
Run(Note that &self
and &mut self
are okay, it’s additional Self
types which
cause this problem.)
In such a case, the compiler cannot predict the return type of foo()
in a
situation like the following:
trait Trait {
fn foo(&self) -> Self;
}
fn call_foo(x: Box<Trait>) {
let y = x.foo(); // What type is y?
// ...
}
RunIf only some methods aren’t object-safe, you can add a where Self: Sized
bound
on them to mark them as explicitly unavailable to trait objects. The
functionality will still be available to all other implementers, including
Box<Trait>
which is itself sized (assuming you impl Trait for Box<Trait>
).
trait Trait {
fn foo(&self) -> Self where Self: Sized;
// more functions
}
RunNow, foo()
can no longer be called on a trait object, but you will now be
allowed to make a trait object, and that will be able to call any object-safe
methods. With such a bound, one can still call foo()
on types implementing
that trait that aren’t behind trait objects.
As mentioned before, trait objects contain pointers to method tables. So, if we have:
trait Trait {
fn foo(&self);
}
impl Trait for String {
fn foo(&self) {
// implementation 1
}
}
impl Trait for u8 {
fn foo(&self) {
// implementation 2
}
}
// ...
RunAt compile time each implementation of Trait
will produce a table containing
the various methods (and other items) related to the implementation.
This works fine, but when the method gains generic parameters, we can have a problem.
Usually, generic parameters get monomorphized. For example, if I have
fn foo<T>(x: T) {
// ...
}
RunThe machine code for foo::<u8>()
, foo::<bool>()
, foo::<String>()
, or any
other type substitution is different. Hence the compiler generates the
implementation on-demand. If you call foo()
with a bool
parameter, the
compiler will only generate code for foo::<bool>()
. When we have additional
type parameters, the number of monomorphized implementations the compiler
generates does not grow drastically, since the compiler will only generate an
implementation if the function is called with unparametrized substitutions
(i.e., substitutions where none of the substituted types are themselves
parameterized).
However, with trait objects we have to make a table containing every object that implements the trait. Now, if it has type parameters, we need to add implementations for every type that implements the trait, and there could theoretically be an infinite number of types.
For example, with:
trait Trait {
fn foo<T>(&self, on: T);
// more methods
}
impl Trait for String {
fn foo<T>(&self, on: T) {
// implementation 1
}
}
impl Trait for u8 {
fn foo<T>(&self, on: T) {
// implementation 2
}
}
// 8 more implementations
RunNow, if we have the following code:
fn call_foo(thing: Box<Trait>) {
thing.foo(true); // this could be any one of the 8 types above
thing.foo(1);
thing.foo("hello");
}
RunWe don’t just need to create a table of all implementations of all methods of
Trait
, we need to create such a table, for each different type fed to
foo()
. In this case this turns out to be (10 types implementing Trait
)*(3
types being fed to foo()
) = 30 implementations!
With real world traits these numbers can grow drastically.
To fix this, it is suggested to use a where Self: Sized
bound similar to the
fix for the sub-error above if you do not intend to call the method with type
parameters:
trait Trait {
fn foo<T>(&self, on: T) where Self: Sized;
// more methods
}
RunIf this is not an option, consider replacing the type parameter with another
trait object (e.g., if T: OtherTrait
, use on: Box<OtherTrait>
). If the
number of types you intend to feed to this method is limited, consider manually
listing out the methods of different types.
Methods that do not take a self
parameter can’t be called since there won’t be
a way to get a pointer to the method table for them.
trait Foo {
fn foo() -> u8;
}
RunThis could be called as <Foo as Foo>::foo()
, which would not be able to pick
an implementation.
Adding a Self: Sized
bound to these methods will generally make this compile.
trait Foo {
fn foo() -> u8 where Self: Sized;
}
RunJust like static functions, associated constants aren’t stored on the method table. If the trait or any subtrait contain an associated constant, they cannot be made into an object.
trait Foo {
const X: i32;
}
impl Foo {}
RunA simple workaround is to use a helper method instead:
trait Foo {
fn x(&self) -> i32;
}
RunSelf
as a type parameter in the supertrait listingThis is similar to the second sub-error, but subtler. It happens in situations like the following:
trait Super<A: ?Sized> {}
trait Trait: Super<Self> {
}
struct Foo;
impl Super<Foo> for Foo{}
impl Trait for Foo {}
fn main() {
let x: Box<dyn Trait>;
}
RunHere, the supertrait might have methods as follows:
trait Super<A: ?Sized> {
fn get_a(&self) -> &A; // note that this is object safe!
}
RunIf the trait Trait
was deriving from something like Super<String>
or
Super<T>
(where Foo
itself is Foo<T>
), this is okay, because given a type
get_a()
will definitely return an object of that type.
However, if it derives from Super<Self>
, even though Super
is object safe,
the method get_a()
would return an object of unknown type when called on the
function. Self
type parameters let us make object safe traits no longer safe,
so they are forbidden when specifying supertraits.
There’s no easy fix for this. Generally, code will need to be refactored so that
you no longer need to derive from Super<Self>
.
It is not allowed to manually call destructors in Rust.
Erroneous code example:
struct Foo {
x: i32,
}
impl Drop for Foo {
fn drop(&mut self) {
println!("kaboom");
}
}
fn main() {
let mut x = Foo { x: -7 };
x.drop(); // error: explicit use of destructor method
}
RunIt is unnecessary to do this since drop
is called automatically whenever a
value goes out of scope. However, if you really need to drop a value by hand,
you can use the std::mem::drop
function:
struct Foo {
x: i32,
}
impl Drop for Foo {
fn drop(&mut self) {
println!("kaboom");
}
}
fn main() {
let mut x = Foo { x: -7 };
drop(x); // ok!
}
RunYou cannot use type or const parameters on foreign items.
Example of erroneous code:
extern "C" { fn some_func<T>(x: T); }
RunTo fix this, replace the generic parameter with the specializations that you need:
extern "C" { fn some_func_i32(x: i32); }
extern "C" { fn some_func_i64(x: i64); }
RunVariadic parameters have been used on a non-C ABI function.
Erroneous code example:
#![feature(unboxed_closures)]
extern "rust-call" {
fn foo(x: u8, ...); // error!
}
RunRust only supports variadic parameters for interoperability with C code in its FFI. As such, variadic parameters can only be used with functions which are using the C ABI. To fix such code, put them in an extern “C” block:
extern "C" {
fn foo (x: u8, ...);
}
RunItems are missing in a trait implementation.
Erroneous code example:
trait Foo {
fn foo();
}
struct Bar;
impl Foo for Bar {}
// error: not all trait items implemented, missing: `foo`
RunWhen trying to make some type implement a trait Foo
, you must, at minimum,
provide implementations for all of Foo
’s required methods (meaning the
methods that do not have default implementations), as well as any required
trait items like associated types or constants. Example:
trait Foo {
fn foo();
}
struct Bar;
impl Foo for Bar {
fn foo() {} // ok!
}
RunAn attempted implementation of a trait method has the wrong number of type or const parameters.
Erroneous code example:
trait Foo {
fn foo<T: Default>(x: T) -> Self;
}
struct Bar;
// error: method `foo` has 0 type parameters but its trait declaration has 1
// type parameter
impl Foo for Bar {
fn foo(x: bool) -> Self { Bar }
}
RunFor example, the Foo
trait has a method foo
with a type parameter T
,
but the implementation of foo
for the type Bar
is missing this parameter.
To fix this error, they must have the same type parameters:
trait Foo {
fn foo<T: Default>(x: T) -> Self;
}
struct Bar;
impl Foo for Bar {
fn foo<T: Default>(x: T) -> Self { // ok!
Bar
}
}
RunAn attempted implementation of a trait method has the wrong number of function parameters.
Erroneous code example:
trait Foo {
fn foo(&self, x: u8) -> bool;
}
struct Bar;
// error: method `foo` has 1 parameter but the declaration in trait `Foo::foo`
// has 2
impl Foo for Bar {
fn foo(&self) -> bool { true }
}
RunFor example, the Foo
trait has a method foo
with two function parameters
(&self
and u8
), but the implementation of foo
for the type Bar
omits
the u8
parameter. To fix this error, they must have the same parameters:
trait Foo {
fn foo(&self, x: u8) -> bool;
}
struct Bar;
impl Foo for Bar {
fn foo(&self, x: u8) -> bool { // ok!
true
}
}
RunThe parameters of any trait method must match between a trait implementation and the trait definition.
Erroneous code example:
trait Foo {
fn foo(x: u16);
fn bar(&self);
}
struct Bar;
impl Foo for Bar {
// error, expected u16, found i16
fn foo(x: i16) { }
// error, types differ in mutability
fn bar(&mut self) { }
}
RunIt is not allowed to cast to a bool.
Erroneous code example:
let x = 5;
// Not allowed, won't compile
let x_is_nonzero = x as bool;
RunIf you are trying to cast a numeric type to a bool, you can compare it with zero instead:
let x = 5;
// Ok
let x_is_nonzero = x != 0;
RunDuring a method call, a value is automatically dereferenced as many times as
needed to make the value’s type match the method’s receiver. The catch is that
the compiler will only attempt to dereference a number of times up to the
recursion limit (which can be set via the recursion_limit
attribute).
For a somewhat artificial example:
#![recursion_limit="4"]
struct Foo;
impl Foo {
fn foo(&self) {}
}
fn main() {
let foo = Foo;
let ref_foo = &&&&&Foo;
// error, reached the recursion limit while auto-dereferencing `&&&&&Foo`
ref_foo.foo();
}
RunOne fix may be to increase the recursion limit. Note that it is possible to create an infinite recursion of dereferencing, in which case the only fix is to somehow break the recursion.
An invalid number of arguments was given when calling a closure.
Erroneous code example:
let f = |x| x * 3;
let a = f(); // invalid, too few parameters
let b = f(4); // this works!
let c = f(2, 3); // invalid, too many parameters
RunWhen invoking closures or other implementations of the function traits Fn
,
FnMut
or FnOnce
using call notation, the number of parameters passed to the
function must match its definition.
A generic function must be treated similarly:
fn foo<F: Fn()>(f: F) {
f(); // this is valid, but f(3) would not work
}
RunThe built-in function traits are generic over a tuple of the function arguments.
If one uses angle-bracket notation (Fn<(T,), Output=U>
) instead of parentheses
(Fn(T) -> U
) to denote the function trait, the type parameter should be a
tuple. Otherwise function call notation cannot be used and the trait will not be
implemented by closures.
The most likely source of this error is using angle-bracket notation without wrapping the function argument type into a tuple, for example:
#![feature(unboxed_closures)]
fn foo<F: Fn<i32>>(f: F) -> F::Output { f(3) }
RunIt can be fixed by adjusting the trait bound like this:
#![feature(unboxed_closures)]
fn foo<F: Fn<(i32,)>>(f: F) -> F::Output { f(3) }
RunNote that (T,)
always denotes the type of a 1-tuple containing an element of
type T
. The comma is necessary for syntactic disambiguation.
External C functions are allowed to be variadic. However, a variadic function
takes a minimum number of arguments. For example, consider C’s variadic printf
function:
use std::os::raw::{c_char, c_int};
extern "C" {
fn printf(_: *const c_char, ...) -> c_int;
}
unsafe { printf(); } // error!
RunUsing this declaration, it must be called with at least one argument, so
simply calling printf()
is invalid. But the following uses are allowed:
unsafe {
use std::ffi::CString;
let fmt = CString::new("test\n").unwrap();
printf(fmt.as_ptr());
let fmt = CString::new("number = %d\n").unwrap();
printf(fmt.as_ptr(), 3);
let fmt = CString::new("%d, %d\n").unwrap();
printf(fmt.as_ptr(), 10, 5);
}
RunAn invalid number of arguments was passed when calling a function.
Erroneous code example:
fn f(u: i32) {}
f(); // error!
RunThe number of arguments passed to a function must match the number of arguments specified in the function signature.
For example, a function like:
fn f(a: u16, b: &str) {}
RunMust always be called with exactly two arguments, e.g., f(2, "test")
.
Note that Rust does not have a notion of optional function arguments or variadic functions (except for its C-FFI).
A struct’s or struct-like enum variant’s field was specified more than once.
Erroneous code example:
struct Foo {
x: i32,
}
fn main() {
let x = Foo {
x: 0,
x: 0, // error: field `x` specified more than once
};
}
RunThis error indicates that during an attempt to build a struct or struct-like enum variant, one of the fields was specified more than once. Each field should be specified exactly one time. Example:
struct Foo {
x: i32,
}
fn main() {
let x = Foo { x: 0 }; // ok!
}
RunA struct’s or struct-like enum variant’s field was not provided.
Erroneous code example:
struct Foo {
x: i32,
y: i32,
}
fn main() {
let x = Foo { x: 0 }; // error: missing field: `y`
}
RunEach field should be specified exactly once. Example:
struct Foo {
x: i32,
y: i32,
}
fn main() {
let x = Foo { x: 0, y: 0 }; // ok!
}
RunAn invalid left-hand side expression was used on an assignment operation.
Erroneous code example:
12 += 1; // error!
RunYou need to have a place expression to be able to assign it something. For example:
let mut x: i8 = 12;
x += 1; // ok!
RunThe compiler found a function whose body contains a return;
statement but
whose return type is not ()
.
Erroneous code example:
// error
fn foo() -> u8 {
return;
}
RunSince return;
is just like return ();
, there is a mismatch between the
function’s return type and the value being returned.
An assignment operator was used on a non-place expression.
Erroneous code examples:
struct SomeStruct {
x: i32,
y: i32,
}
const SOME_CONST: i32 = 12;
fn some_other_func() {}
fn some_function() {
SOME_CONST = 14; // error: a constant value cannot be changed!
1 = 3; // error: 1 isn't a valid place!
some_other_func() = 4; // error: we cannot assign value to a function!
SomeStruct::x = 12; // error: SomeStruct a structure name but it is used
// like a variable!
}
RunThe left-hand side of an assignment operator must be a place expression. A place expression represents a memory location and can be a variable (with optional namespacing), a dereference, an indexing expression or a field reference.
More details can be found in the Expressions section of the Reference.
And now let’s give working examples:
struct SomeStruct {
x: i32,
y: i32,
}
let mut s = SomeStruct { x: 0, y: 0 };
s.x = 3; // that's good !
// ...
fn some_func(x: &mut i32) {
*x = 12; // that's good !
}
RunA structure-literal syntax was used to create an item that is not a structure or enum variant.
Example of erroneous code:
type U32 = u32;
let t = U32 { value: 4 }; // error: expected struct, variant or union type,
// found builtin type `u32`
RunTo fix this, ensure that the name was correctly spelled, and that the correct form of initializer was used.
For example, the code above can be fixed to:
type U32 = u32;
let t: U32 = 4;
Runor:
struct U32 { value: u32 }
let t = U32 { value: 4 };
RunA recursive type has infinite size because it doesn’t have an indirection.
Erroneous code example:
struct ListNode {
head: u8,
tail: Option<ListNode>, // error: no indirection here so impossible to
// compute the type's size
}
RunWhen defining a recursive struct or enum, any use of the type being defined
from inside the definition must occur behind a pointer (like Box
, &
or
Rc
). This is because structs and enums must have a well-defined size, and
without the pointer, the size of the type would need to be unbounded.
In the example, the type cannot have a well-defined size, because it needs to be
arbitrarily large (since we would be able to nest ListNode
s to any depth).
Specifically,
size of `ListNode` = 1 byte for `head`
+ 1 byte for the discriminant of the `Option`
+ size of `ListNode`
One way to fix this is by wrapping ListNode
in a Box
, like so:
struct ListNode {
head: u8,
tail: Option<Box<ListNode>>,
}
RunThis works because Box
is a pointer, so its size is well-known.
You cannot define a struct (or enum) Foo
that requires an instance of Foo
in order to make a new Foo
value. This is because there would be no way a
first instance of Foo
could be made to initialize another instance!
Here’s an example of a struct that has this problem:
struct Foo { x: Box<Foo> } // error
RunOne fix is to use Option
, like so:
struct Foo { x: Option<Box<Foo>> }
RunNow it’s possible to create at least one instance of Foo
: Foo { x: None }
.
When using the #[simd]
attribute on a tuple struct, the components of the
tuple struct must all be of a concrete, nongeneric type so the compiler can
reason about how to use SIMD with them. This error will occur if the types
are generic.
This will cause an error:
#![feature(repr_simd)]
#[repr(simd)]
struct Bad<T>(T, T, T, T);
RunThis will not:
#![feature(repr_simd)]
#[repr(simd)]
struct Good(u32, u32, u32, u32);
RunA #[simd]
attribute was applied to an empty tuple struct.
Erroneous code example:
#![feature(repr_simd)]
#[repr(simd)]
struct Bad; // error!
RunThe #[simd]
attribute can only be applied to non empty tuple structs, because
it doesn’t make sense to try to use SIMD operations when there are no values to
operate on.
Fixed example:
#![feature(repr_simd)]
#[repr(simd)]
struct Good(u32); // ok!
RunAll types in a tuple struct aren’t the same when using the #[simd]
attribute.
Erroneous code example:
#![feature(repr_simd)]
#[repr(simd)]
struct Bad(u16, u32, u32 u32); // error!
RunWhen using the #[simd]
attribute to automatically use SIMD operations in tuple
struct, the types in the struct must all be of the same type, or the compiler
will trigger this error.
Fixed example:
#![feature(repr_simd)]
#[repr(simd)]
struct Good(u32, u32, u32, u32); // ok!
RunA tuple struct’s element isn’t a machine type when using the #[simd]
attribute.
Erroneous code example:
#![feature(repr_simd)]
#[repr(simd)]
struct Bad(String); // error!
RunWhen using the #[simd]
attribute on a tuple struct, the elements in the tuple
must be machine types so SIMD operations can be applied to them.
Fixed example:
#![feature(repr_simd)]
#[repr(simd)]
struct Good(u32, u32, u32, u32); // ok!
RunA constant value failed to get evaluated.
Erroneous code example:
enum Enum {
X = (1 << 500),
Y = (1 / 0),
}
RunThis error indicates that the compiler was unable to sensibly evaluate a constant expression that had to be evaluated. Attempting to divide by 0 or causing an integer overflow are two ways to induce this error.
Ensure that the expressions given can be evaluated as the desired integer type.
See the Custom Discriminants section of the Reference
for more information about setting custom integer types on fieldless enums
using the repr
attribute.
A discriminant value is present more than once.
Erroneous code example:
enum Enum {
P = 3,
X = 3, // error!
Y = 5,
}
RunEnum discriminants are used to differentiate enum variants stored in memory. This error indicates that the same value was used for two or more variants, making it impossible to distinguish them.
enum Enum {
P,
X = 3, // ok!
Y = 5,
}
RunNote that variants without a manually specified discriminant are numbered from top to bottom starting from 0, so clashes can occur with seemingly unrelated variants.
enum Bad {
X,
Y = 0, // error!
}
RunHere X
will have already been specified the discriminant 0 by the time Y
is
encountered, so a conflict occurs.
An unsupported representation was attempted on a zero-variant enum.
Erroneous code example:
#[repr(i32)]
enum NightsWatch {} // error: unsupported representation for zero-variant enum
RunIt is impossible to define an integer type to be used to represent zero-variant enum values because there are no zero-variant enum values. There is no way to construct an instance of the following type using only safe code. So you have two solutions. Either you add variants in your enum:
#[repr(i32)]
enum NightsWatch {
JonSnow,
Commander,
}
Runor you remove the integer representation of your enum:
enum NightsWatch {}
RunToo many type arguments were supplied for a function. For example:
fn foo<T>() {}
fn main() {
foo::<f64, bool>(); // error: wrong number of type arguments:
// expected 1, found 2
}
RunThe number of supplied arguments must exactly match the number of defined type parameters.
You gave too many lifetime arguments. Erroneous code example:
fn f() {}
fn main() {
f::<'static>() // error: wrong number of lifetime arguments:
// expected 0, found 1
}
RunPlease check you give the right number of lifetime arguments. Example:
fn f() {}
fn main() {
f() // ok!
}
RunIt’s also important to note that the Rust compiler can generally determine the lifetime by itself. Example:
struct Foo {
value: String
}
impl Foo {
// it can be written like this
fn get_value<'a>(&'a self) -> &'a str { &self.value }
// but the compiler works fine with this too:
fn without_lifetime(&self) -> &str { &self.value }
}
fn main() {
let f = Foo { value: "hello".to_owned() };
println!("{}", f.get_value());
println!("{}", f.without_lifetime());
}
RunToo few type arguments were supplied for a function. For example:
fn foo<T, U>() {}
fn main() {
foo::<f64>(); // error: wrong number of type arguments: expected 2, found 1
}
RunNote that if a function takes multiple type arguments but you want the compiler to infer some of them, you can use type placeholders:
fn foo<T, U>(x: T) {}
fn main() {
let x: bool = true;
foo::<f64>(x); // error: wrong number of type arguments:
// expected 2, found 1
foo::<_, f64>(x); // same as `foo::<bool, f64>(x)`
}
RunYou gave too few lifetime arguments. Example:
fn foo<'a: 'b, 'b: 'a>() {}
fn main() {
foo::<'static>(); // error: wrong number of lifetime arguments:
// expected 2, found 1
}
RunPlease check you give the right number of lifetime arguments. Example:
fn foo<'a: 'b, 'b: 'a>() {}
fn main() {
foo::<'static, 'static>();
}
RunAn unnecessary type or const parameter was given in a type alias.
Erroneous code example:
type Foo<T> = u32; // error: type parameter `T` is unused
// or:
type Foo<A,B> = Box<A>; // error: type parameter `B` is unused
RunPlease check you didn’t write too many parameters. Example:
type Foo = u32; // ok!
type Foo2<A> = Box<A>; // ok!
RunAn undefined atomic operation function was declared.
Erroneous code example:
#![feature(intrinsics)]
extern "rust-intrinsic" {
fn atomic_foo(); // error: unrecognized atomic operation
// function
}
RunPlease check you didn’t make a mistake in the function’s name. All intrinsic
functions are defined in compiler/rustc_codegen_llvm/src/intrinsic.rs
and in
library/core/src/intrinsics.rs
in the Rust source code. Example:
#![feature(intrinsics)]
extern "rust-intrinsic" {
fn atomic_fence(); // ok!
}
RunAn unknown intrinsic function was declared.
Erroneous code example:
#![feature(intrinsics)]
extern "rust-intrinsic" {
fn foo(); // error: unrecognized intrinsic function: `foo`
}
fn main() {
unsafe {
foo();
}
}
RunPlease check you didn’t make a mistake in the function’s name. All intrinsic
functions are defined in compiler/rustc_codegen_llvm/src/intrinsic.rs
and in
library/core/src/intrinsics.rs
in the Rust source code. Example:
#![feature(intrinsics)]
extern "rust-intrinsic" {
fn atomic_fence(); // ok!
}
fn main() {
unsafe {
atomic_fence();
}
}
RunAn invalid number of generic parameters was passed to an intrinsic function.
Erroneous code example:
#![feature(intrinsics)]
extern "rust-intrinsic" {
fn size_of<T, U>() -> usize; // error: intrinsic has wrong number
// of type parameters
}
RunPlease check that you provided the right number of type parameters and verify with the function declaration in the Rust source code. Example:
#![feature(intrinsics)]
extern "rust-intrinsic" {
fn size_of<T>() -> usize; // ok!
}
RunThis error indicates that a lifetime is missing from a type. If it is an error inside a function signature, the problem may be with failing to adhere to the lifetime elision rules (see below).
Erroneous code examples:
struct Foo1 { x: &bool }
// ^ expected lifetime parameter
struct Foo2<'a> { x: &'a bool } // correct
struct Bar1 { x: Foo2 }
// ^^^^ expected lifetime parameter
struct Bar2<'a> { x: Foo2<'a> } // correct
enum Baz1 { A(u8), B(&bool), }
// ^ expected lifetime parameter
enum Baz2<'a> { A(u8), B(&'a bool), } // correct
type MyStr1 = &str;
// ^ expected lifetime parameter
type MyStr2<'a> = &'a str; // correct
RunLifetime elision is a special, limited kind of inference for lifetimes in function signatures which allows you to leave out lifetimes in certain cases. For more background on lifetime elision see the book.
The lifetime elision rules require that any function signature with an elided output lifetime must either have:
&self
or &mut self
receiverIn the first case, the output lifetime is inferred to be the same as the unique
input lifetime. In the second case, the lifetime is instead inferred to be the
same as the lifetime on &self
or &mut self
.
Here are some examples of elision errors:
// error, no input lifetimes
fn foo() -> &str { }
// error, `x` and `y` have distinct lifetimes inferred
fn bar(x: &str, y: &str) -> &str { }
// error, `y`'s lifetime is inferred to be distinct from `x`'s
fn baz<'a>(x: &'a str, y: &str) -> &str { }
RunAn incorrect number of generic arguments was provided.
Erroneous code example:
struct Foo<T> { x: T }
struct Bar { x: Foo } // error: wrong number of type arguments:
// expected 1, found 0
struct Baz<S, T> { x: Foo<S, T> } // error: wrong number of type arguments:
// expected 1, found 2
fn foo<T, U>(x: T, y: U) {}
fn f() {}
fn main() {
let x: bool = true;
foo::<bool>(x); // error: wrong number of type arguments:
// expected 2, found 1
foo::<bool, i32, i32>(x, 2, 4); // error: wrong number of type arguments:
// expected 2, found 3
f::<'static>(); // error: wrong number of lifetime arguments
// expected 0, found 1
}
RunWhen using/declaring an item with generic arguments, you must provide the exact same number:
struct Foo<T> { x: T }
struct Bar<T> { x: Foo<T> } // ok!
struct Baz<S, T> { x: Foo<S>, y: Foo<T> } // ok!
fn foo<T, U>(x: T, y: U) {}
fn f() {}
fn main() {
let x: bool = true;
foo::<bool, u32>(x, 12); // ok!
f(); // ok!
}
RunYou tried to provide a generic argument to a type which doesn’t need it.
Erroneous code example:
type X = u32<i32>; // error: type arguments are not allowed for this type
type Y = bool<'static>; // error: lifetime parameters are not allowed on
// this type
RunCheck that you used the correct argument and that the definition is correct.
Example:
type X = u32; // ok!
type Y = bool; // ok!
RunNote that generic arguments for enum variant constructors go after the variant,
not after the enum. For example, you would write Option::None::<u32>
,
rather than Option::<u32>::None
.
You tried to provide a lifetime to a type which doesn’t need it.
See E0109
for more details.
An inherent implementation was defined for a type outside the current crate.
Erroneous code example:
impl Vec<u8> { } // error
RunYou can only define an inherent implementation for a type in the same crate
where the type was defined. For example, an impl
block as above is not allowed
since Vec
is defined in the standard library.
To fix this problem, you can either:
Note that using the type
keyword does not work here because type
only
introduces a type alias:
type Bytes = Vec<u8>;
impl Bytes { } // error, same as above
RunOnly traits defined in the current crate can be implemented for arbitrary types.
Erroneous code example:
impl Drop for u32 {}
RunThis error indicates a violation of one of Rust’s orphan rules for trait implementations. The rule prohibits any implementation of a foreign trait (a trait defined in another crate) where
To avoid this kind of error, ensure that at least one local type is referenced
by the impl
:
pub struct Foo; // you define your type in your crate
impl Drop for Foo { // and you can implement the trait on it!
// code of trait implementation here
}
impl From<Foo> for i32 { // or you use a type from your crate as
// a type parameter
fn from(i: Foo) -> i32 {
0
}
}
RunAlternatively, define a trait locally and implement that instead:
trait Bar {
fn get(&self) -> usize;
}
impl Bar for u32 {
fn get(&self) -> usize { 0 }
}
RunFor information on the design of the orphan rules, see RFC 1023.
An inherent implementation was defined for something which isn’t a struct, enum, union, or trait object.
Erroneous code example:
impl (u8, u8) { // error: no nominal type found for inherent implementation
fn get_state(&self) -> String {
// ...
}
}
RunTo fix this error, please implement a trait on the type or wrap it in a struct. Example:
// we create a trait here
trait LiveLongAndProsper {
fn get_state(&self) -> String;
}
// and now you can implement it on (u8, u8)
impl LiveLongAndProsper for (u8, u8) {
fn get_state(&self) -> String {
"He's dead, Jim!".to_owned()
}
}
RunAlternatively, you can create a newtype. A newtype is a wrapping tuple-struct.
For example, NewType
is a newtype over Foo
in struct NewType(Foo)
.
Example:
struct TypeWrapper((u8, u8));
impl TypeWrapper {
fn get_state(&self) -> String {
"Fascinating!".to_owned()
}
}
RunInstead of defining an inherent implementation on a reference, you could also move the reference inside the implementation:
struct Foo;
impl &Foo { // error: no nominal type found for inherent implementation
fn bar(self, other: Self) {}
}
Runbecomes
struct Foo;
impl Foo {
fn bar(&self, other: &Self) {}
}
RunThere are conflicting trait implementations for the same type.
Erroneous code example:
trait MyTrait {
fn get(&self) -> usize;
}
impl<T> MyTrait for T {
fn get(&self) -> usize { 0 }
}
struct Foo {
value: usize
}
impl MyTrait for Foo { // error: conflicting implementations of trait
// `MyTrait` for type `Foo`
fn get(&self) -> usize { self.value }
}
RunWhen looking for the implementation for the trait, the compiler finds
both the impl<T> MyTrait for T
where T is all types and the impl MyTrait for Foo
. Since a trait cannot be implemented multiple times,
this is an error. So, when you write:
trait MyTrait {
fn get(&self) -> usize;
}
impl<T> MyTrait for T {
fn get(&self) -> usize { 0 }
}
RunThis makes the trait implemented on all types in the scope. So if you try to implement it on another one after that, the implementations will conflict. Example:
trait MyTrait {
fn get(&self) -> usize;
}
impl<T> MyTrait for T {
fn get(&self) -> usize { 0 }
}
struct Foo;
fn main() {
let f = Foo;
f.get(); // the trait is implemented so we can use it
}
RunDrop was implemented on a trait, which is not allowed: only structs and enums can implement Drop.
Erroneous code example:
trait MyTrait {}
impl Drop for MyTrait {
fn drop(&mut self) {}
}
RunA workaround for this problem is to wrap the trait up in a struct, and implement Drop on that:
trait MyTrait {}
struct MyWrapper<T: MyTrait> { foo: T }
impl <T: MyTrait> Drop for MyWrapper<T> {
fn drop(&mut self) {}
}
RunAlternatively, wrapping trait objects requires something:
trait MyTrait {}
//or Box<MyTrait>, if you wanted an owned trait object
struct MyWrapper<'a> { foo: &'a MyTrait }
impl <'a> Drop for MyWrapper<'a> {
fn drop(&mut self) {}
}
RunThe type placeholder _
was used within a type on an item’s signature.
Erroneous code example:
fn foo() -> _ { 5 } // error
static BAR: _ = "test"; // error
RunIn those cases, you need to provide the type explicitly:
fn foo() -> i32 { 5 } // ok!
static BAR: &str = "test"; // ok!
RunThe type placeholder _
can be used outside item’s signature as follows:
let x = "a4a".split('4')
.collect::<Vec<_>>(); // No need to precise the Vec's generic type.
RunA struct was declared with two fields having the same name.
Erroneous code example:
struct Foo {
field1: i32,
field1: i32, // error: field is already declared
}
RunPlease verify that the field names have been correctly spelled. Example:
struct Foo {
field1: i32,
field2: i32, // ok!
}
RunA type parameter with default value is using forward declared identifier.
Erroneous code example:
struct Foo<T = U, U = ()> {
field1: T,
field2: U,
}
// error: generic parameters with a default cannot use forward declared
// identifiers
RunType parameter defaults can only use parameters that occur before them. Since type parameters are evaluated in-order, this issue could be fixed by doing:
struct Foo<U = (), T = U> {
field1: T,
field2: U,
}
RunPlease also verify that this wasn’t because of a name-clash and rename the type parameter if so.
A pattern was declared as an argument in a foreign function declaration.
Erroneous code example:
extern "C" {
fn foo((a, b): (u32, u32)); // error: patterns aren't allowed in foreign
// function declarations
}
RunTo fix this error, replace the pattern argument with a regular one. Example:
struct SomeStruct {
a: u32,
b: u32,
}
extern "C" {
fn foo(s: SomeStruct); // ok!
}
RunOr:
extern "C" {
fn foo(a: (u32, u32)); // ok!
}
RunThe main
function was defined with generic parameters.
Erroneous code example:
fn main<T>() { // error: main function is not allowed to have generic parameters
}
RunIt is not possible to define the main
function with generic parameters.
It must not take any arguments.
A function with the start
attribute was declared with type parameters.
Erroneous code example:
#![feature(start)]
#[start]
fn f<T>() {}
RunIt is not possible to declare type parameters on a function that has the start
attribute. Such a function must have the following type signature (for more
information, view the unstable book):
fn(isize, *const *const u8) -> isize;
RunExample:
#![feature(start)]
#[start]
fn my_start(argc: isize, argv: *const *const u8) -> isize {
0
}
RunUnsafe code was used outside of an unsafe function or block.
Erroneous code example:
unsafe fn f() { return; } // This is the unsafe code
fn main() {
f(); // error: call to unsafe function requires unsafe function or block
}
RunUsing unsafe functionality is potentially dangerous and disallowed by safety checks. Examples:
These safety checks can be relaxed for a section of the code by wrapping the
unsafe instructions with an unsafe
block. For instance:
unsafe fn f() { return; }
fn main() {
unsafe { f(); } // ok!
}
RunSee the unsafe section of the Book for more details.
More than one main
function was found.
Erroneous code example:
fn main() {
// ...
}
// ...
fn main() { // error!
// ...
}
RunA binary can only have one entry point, and by default that entry point is the
main()
function. If there are multiple instances of this function, please
rename one of them.
More than one function was declared with the #[main]
attribute.
Erroneous code example:
#![feature(main)]
#[main]
fn foo() {}
#[main]
fn f() {} // error: multiple functions with a `#[main]` attribute
RunThis error indicates that the compiler found multiple functions with the
#[main]
attribute. This is an error because there must be a unique entry
point into a Rust program. Example:
#![feature(main)]
#[main]
fn f() {} // ok!
RunMore than one function was declared with the #[start]
attribute.
Erroneous code example:
#![feature(start)]
#[start]
fn foo(argc: isize, argv: *const *const u8) -> isize {}
#[start]
fn f(argc: isize, argv: *const *const u8) -> isize {}
// error: multiple 'start' functions
RunThis error indicates that the compiler found multiple functions with the
#[start]
attribute. This is an error because there must be a unique entry
point into a Rust program. Example:
#![feature(start)]
#[start]
fn foo(argc: isize, argv: *const *const u8) -> isize { 0 } // ok!
RunThere are various restrictions on transmuting between types in Rust; for example types being transmuted must have the same size. To apply all these restrictions, the compiler must know the exact types that may be transmuted. When type parameters are involved, this cannot always be done.
So, for example, the following is not allowed:
use std::mem::transmute;
struct Foo<T>(Vec<T>);
fn foo<T>(x: Vec<T>) {
// we are transmuting between Vec<T> and Foo<F> here
let y: Foo<T> = unsafe { transmute(x) };
// do something with y
}
RunIn this specific case there’s a good chance that the transmute is harmless (but
this is not guaranteed by Rust). However, when alignment and enum optimizations
come into the picture, it’s quite likely that the sizes may or may not match
with different type parameter substitutions. It’s not possible to check this for
all possible types, so transmute()
simply only accepts types without any
unsubstituted type parameters.
If you need this, there’s a good chance you’re doing something wrong. Keep in mind that Rust doesn’t guarantee much about the layout of different structs (even two structs with identical declarations may have different layouts). If there is a solution that avoids the transmute entirely, try it instead.
If it’s possible, hand-monomorphize the code by writing the function for each possible type substitution. It’s possible to use traits to do this cleanly, for example:
use std::mem::transmute;
struct Foo<T>(Vec<T>);
trait MyTransmutableType: Sized {
fn transmute(_: Vec<Self>) -> Foo<Self>;
}
impl MyTransmutableType for u8 {
fn transmute(x: Vec<u8>) -> Foo<u8> {
unsafe { transmute(x) }
}
}
impl MyTransmutableType for String {
fn transmute(x: Vec<String>) -> Foo<String> {
unsafe { transmute(x) }
}
}
// ... more impls for the types you intend to transmute
fn foo<T: MyTransmutableType>(x: Vec<T>) {
let y: Foo<T> = <T as MyTransmutableType>::transmute(x);
// do something with y
}
RunEach impl will be checked for a size match in the transmute as usual, and since there are no unbound type parameters involved, this should compile unless there is a size mismatch in one of the impls.
It is also possible to manually transmute:
unsafe {
ptr::read(&v as *const _ as *const SomeType) // `v` transmuted to `SomeType`
}
RunNote that this does not move v
(unlike transmute
), and may need a
call to mem::forget(v)
in case you want to avoid destructors being called.
A lang item was redefined.
Erroneous code example:
#![feature(lang_items)]
#[lang = "owned_box"]
struct Foo<T>(T); // error: duplicate lang item found: `owned_box`
RunLang items are already implemented in the standard library. Unless you are writing a free-standing application (e.g., a kernel), you do not need to provide them yourself.
You can build a free-standing crate by adding #![no_std]
to the crate
attributes:
#![no_std]
RunSee also the unstable book.
Imports (use
statements) are not allowed after non-item statements, such as
variable declarations and expression statements.
Here is an example that demonstrates the error:
fn f() {
// Variable declaration before import
let x = 0;
use std::io::Read;
// ...
}
RunThe solution is to declare the imports at the top of the block, function, or file.
Here is the previous example again, with the correct order:
fn f() {
use std::io::Read;
let x = 0;
// ...
}
RunSee the Declaration Statements section of the reference for more information about what constitutes an item declaration and what does not.
An associated const has been referenced in a pattern.
Erroneous code example:
enum EFoo { A, B, C, D }
trait Foo {
const X: EFoo;
}
fn test<A: Foo>(arg: EFoo) {
match arg {
A::X => { // error!
println!("A::X");
}
}
}
Runconst
and static
mean different things. A const
is a compile-time
constant, an alias for a literal value. This property means you can match it
directly within a pattern.
The static
keyword, on the other hand, guarantees a fixed location in memory.
This does not always mean that the value is constant. For example, a global
mutex can be declared static
as well.
If you want to match against a static
, consider using a guard instead:
static FORTY_TWO: i32 = 42;
match Some(42) {
Some(x) if x == FORTY_TWO => {}
_ => {}
}
RunA value was moved whose size was not known at compile time.
Erroneous code example:
#![feature(box_syntax)]
trait Bar {
fn f(self);
}
impl Bar for i32 {
fn f(self) {}
}
fn main() {
let b: Box<dyn Bar> = box (0 as i32);
b.f();
// error: cannot move a value of type dyn Bar: the size of dyn Bar cannot
// be statically determined
}
RunIn Rust, you can only move a value when its size is known at compile time.
To work around this restriction, consider “hiding” the value behind a reference:
either &x
or &mut x
. Since a reference has a fixed size, this lets you move
it around as usual. Example:
#![feature(box_syntax)]
trait Bar {
fn f(&self);
}
impl Bar for i32 {
fn f(&self) {}
}
fn main() {
let b: Box<dyn Bar> = box (0 as i32);
b.f();
// ok!
}
RunAn if let
pattern attempts to match the pattern, and enters the body if the
match was successful. If the match is irrefutable (when it cannot fail to
match), use a regular let
-binding instead. For instance:
struct Irrefutable(i32);
let irr = Irrefutable(0);
// This fails to compile because the match is irrefutable.
if let Irrefutable(x) = irr {
// This body will always be executed.
// ...
}
RunTry this instead:
struct Irrefutable(i32);
let irr = Irrefutable(0);
let Irrefutable(x) = irr;
println!("{}", x);
RunSomething which is neither a tuple struct nor a tuple variant was used as a pattern.
Erroneous code example:
enum A {
B,
C,
}
impl A {
fn new() {}
}
fn bar(foo: A) {
match foo {
A::new() => (), // error!
_ => {}
}
}
RunThis error means that an attempt was made to match something which is neither a tuple struct nor a tuple variant. Only these two elements are allowed as a pattern:
enum A {
B,
C,
}
impl A {
fn new() {}
}
fn bar(foo: A) {
match foo {
A::B => (), // ok!
_ => {}
}
}
RunA while let
pattern attempts to match the pattern, and enters the body if the
match was successful. If the match is irrefutable (when it cannot fail to
match), use a regular let
-binding inside a loop
instead. For instance:
struct Irrefutable(i32);
let irr = Irrefutable(0);
// This fails to compile because the match is irrefutable.
while let Irrefutable(x) = irr {
// ...
}
RunTry this instead:
struct Irrefutable(i32);
let irr = Irrefutable(0);
loop {
let Irrefutable(x) = irr;
// ...
}
RunA pattern binding is using the same name as one of the variants of a type.
Erroneous code example:
enum Method {
GET,
POST,
}
fn is_empty(s: Method) -> bool {
match s {
GET => true,
_ => false
}
}
fn main() {}
RunEnum variants are qualified by default. For example, given this type:
enum Method {
GET,
POST,
}
RunYou would match it using:
enum Method {
GET,
POST,
}
let m = Method::GET;
match m {
Method::GET => {},
Method::POST => {},
}
RunIf you don’t qualify the names, the code will bind new variables named “GET” and
“POST” instead. This behavior is likely not what you want, so rustc
warns when
that happens.
Qualified names are good practice, and most code works well with them. But if you prefer them unqualified, you can import the variants into scope:
use Method::*;
enum Method { GET, POST }
RunIf you want others to be able to import variants from your module directly, use
pub use
:
pub use Method::*;
pub enum Method { GET, POST }
RunThe +
type operator was used in an ambiguous context.
Erroneous code example:
trait Foo {}
struct Bar<'a> {
x: &'a Foo + 'a, // error!
y: &'a mut Foo + 'a, // error!
z: fn() -> Foo + 'a, // error!
}
RunIn types, the +
type operator has low precedence, so it is often necessary
to use parentheses:
trait Foo {}
struct Bar<'a> {
x: &'a (Foo + 'a), // ok!
y: &'a mut (Foo + 'a), // ok!
z: fn() -> (Foo + 'a), // ok!
}
RunMore details can be found in RFC 438.
Manual implemetation of a Fn*
trait.
Erroneous code example:
struct MyClosure {
foo: i32
}
impl FnOnce<()> for MyClosure { // error
type Output = ();
extern "rust-call" fn call_once(self, args: ()) -> Self::Output {
println!("{}", self.foo);
}
}
RunManually implementing Fn
, FnMut
or FnOnce
is unstable
and requires #![feature(fn_traits, unboxed_closures)]
.
#![feature(fn_traits, unboxed_closures)]
struct MyClosure {
foo: i32
}
impl FnOnce<()> for MyClosure { // ok!
type Output = ();
extern "rust-call" fn call_once(self, args: ()) -> Self::Output {
println!("{}", self.foo);
}
}
RunThe argumements must be a tuple representing the argument list. For more info, see the tracking issue:
The Copy
trait was implemented on a type with a Drop
implementation.
Erroneous code example:
#[derive(Copy)]
struct Foo; // error!
impl Drop for Foo {
fn drop(&mut self) {
}
}
RunExplicitly implementing both Drop
and Copy
trait on a type is currently
disallowed. This feature can make some sense in theory, but the current
implementation is incorrect and can lead to memory unsafety (see
issue #20126), so it has been disabled for now.
An associated function for a trait was defined to be static, but an
implementation of the trait declared the same function to be a method (i.e., to
take a self
parameter).
Erroneous code example:
trait Foo {
fn foo();
}
struct Bar;
impl Foo for Bar {
// error, method `foo` has a `&self` declaration in the impl, but not in
// the trait
fn foo(&self) {}
}
RunWhen a type implements a trait’s associated function, it has to use the same
signature. So in this case, since Foo::foo
does not take any argument and
does not return anything, its implementation on Bar
should be the same:
trait Foo {
fn foo();
}
struct Bar;
impl Foo for Bar {
fn foo() {} // ok!
}
RunAn associated function for a trait was defined to be a method (i.e., to take a
self
parameter), but an implementation of the trait declared the same function
to be static.
Erroneous code example:
trait Foo {
fn foo(&self);
}
struct Bar;
impl Foo for Bar {
// error, method `foo` has a `&self` declaration in the trait, but not in
// the impl
fn foo() {}
}
RunWhen a type implements a trait’s associated function, it has to use the same
signature. So in this case, since Foo::foo
takes self
as argument and
does not return anything, its implementation on Bar
should be the same:
trait Foo {
fn foo(&self);
}
struct Bar;
impl Foo for Bar {
fn foo(&self) {} // ok!
}
RunAn associated type wasn’t specified for a trait object.
Erroneous code example:
trait Trait {
type Bar;
}
type Foo = Trait; // error: the value of the associated type `Bar` (from
// the trait `Trait`) must be specified
RunTrait objects need to have all associated types specified. Please verify that all associated types of the trait were specified and the correct trait was used. Example:
trait Trait {
type Bar;
}
type Foo = Trait<Bar=i32>; // ok!
Runwhere
clauses must use generic type parameters: it does not make sense to use
them otherwise. An example causing this error:
trait Foo {
fn bar(&self);
}
#[derive(Copy,Clone)]
struct Wrapper<T> {
Wrapped: T
}
impl Foo for Wrapper<u32> where Wrapper<u32>: Clone {
fn bar(&self) { }
}
RunThis use of a where
clause is strange - a more common usage would look
something like the following:
trait Foo {
fn bar(&self);
}
#[derive(Copy,Clone)]
struct Wrapper<T> {
Wrapped: T
}
impl <T> Foo for Wrapper<T> where Wrapper<T>: Clone {
fn bar(&self) { }
}
RunHere, we’re saying that the implementation exists on Wrapper only when the
wrapped type T
implements Clone
. The where
clause is important because
some types will not implement Clone
, and thus will not get this method.
In our erroneous example, however, we’re referencing a single concrete type.
Since we know for certain that Wrapper<u32>
implements Clone
, there’s no
reason to also specify it in a where
clause.
The lifetime parameters of the method do not match the trait declaration.
Erroneous code example:
trait Trait {
fn bar<'a,'b:'a>(x: &'a str, y: &'b str);
}
struct Foo;
impl Trait for Foo {
fn bar<'a,'b>(x: &'a str, y: &'b str) {
// error: lifetime parameters or bounds on method `bar`
// do not match the trait declaration
}
}
RunThe lifetime constraint 'b
for bar()
implementation does not match the
trait declaration. Ensure lifetime declarations match exactly in both trait
declaration and implementation. Example:
trait Trait {
fn t<'a,'b:'a>(x: &'a str, y: &'b str);
}
struct Foo;
impl Trait for Foo {
fn t<'a,'b:'a>(x: &'a str, y: &'b str) { // ok!
}
}
RunAn inherent implementation was marked unsafe.
Erroneous code example:
struct Foo;
unsafe impl Foo { } // error!
RunInherent implementations (one that do not implement a trait but provide
methods associated with a type) are always safe because they are not
implementing an unsafe trait. Removing the unsafe
keyword from the inherent
implementation will resolve this error.
struct Foo;
impl Foo { } // ok!
RunA negative implementation was marked as unsafe.
Erroneous code example:
struct Foo;
unsafe impl !Clone for Foo { } // error!
RunA negative implementation is one that excludes a type from implementing a particular trait. Not being able to use a trait is always a safe operation, so negative implementations are always safe and never need to be marked as unsafe.
This will compile:
#![feature(auto_traits)]
struct Foo;
auto trait Enterprise {}
impl !Enterprise for Foo { }
RunPlease note that negative impls are only allowed for auto traits.
A trait implementation was marked as unsafe while the trait is safe.
Erroneous code example:
struct Foo;
trait Bar { }
unsafe impl Bar for Foo { } // error!
RunSafe traits should not have unsafe implementations, therefore marking an implementation for a safe trait unsafe will cause a compiler error. Removing the unsafe marker on the trait noted in the error will resolve this problem:
struct Foo;
trait Bar { }
impl Bar for Foo { } // ok!
RunAn unsafe trait was implemented without an unsafe implementation.
Erroneous code example:
struct Foo;
unsafe trait Bar { }
impl Bar for Foo { } // error!
RunUnsafe traits must have unsafe implementations. This error occurs when an implementation for an unsafe trait isn’t marked as unsafe. This may be resolved by marking the unsafe implementation as unsafe.
struct Foo;
unsafe trait Bar { }
unsafe impl Bar for Foo { } // ok!
RunTwo associated items (like methods, associated types, associated functions, etc.) were defined with the same identifier.
Erroneous code example:
struct Foo(u8);
impl Foo {
fn bar(&self) -> bool { self.0 > 5 }
fn bar() {} // error: duplicate associated function
}
trait Baz {
type Quux;
fn baz(&self) -> bool;
}
impl Baz for Foo {
type Quux = u32;
fn baz(&self) -> bool { true }
// error: duplicate method
fn baz(&self) -> bool { self.0 > 5 }
// error: duplicate associated type
type Quux = u32;
}
RunNote, however, that items with the same name are allowed for inherent impl
blocks that don’t overlap:
struct Foo<T>(T);
impl Foo<u8> {
fn bar(&self) -> bool { self.0 > 5 }
}
impl Foo<bool> {
fn bar(&self) -> bool { self.0 }
}
RunHaving multiple relaxed default bounds is unsupported.
Erroneous code example:
struct Bad<T: ?Sized + ?Send>{
inner: T
}
RunHere the type T
cannot have a relaxed bound for multiple default traits
(Sized
and Send
). This can be fixed by only using one relaxed bound.
struct Good<T: ?Sized>{
inner: T
}
RunThe Copy
trait was implemented on a type which contains a field that doesn’t
implement the Copy
trait.
Erroneous code example:
struct Foo {
foo: Vec<u32>,
}
impl Copy for Foo { } // error!
RunThe Copy
trait is implemented by default only on primitive types. If your
type only contains primitive types, you’ll be able to implement Copy
on it.
Otherwise, it won’t be possible.
Here’s another example that will fail:
#[derive(Copy)] // error!
struct Foo<'a> {
ty: &'a mut bool,
}
RunThis fails because &mut T
is not Copy
, even when T
is Copy
(this
differs from the behavior for &T
, which is always Copy
).
An attempt to implement the Copy
trait for an enum failed because one of the
variants does not implement Copy
. To fix this, you must implement Copy
for
the mentioned variant. Note that this may not be possible, as in the example of
enum Foo {
Bar(Vec<u32>),
Baz,
}
impl Copy for Foo { }
RunThis fails because Vec<T>
does not implement Copy
for any T
.
Here’s another example that will fail:
#[derive(Copy)]
enum Foo<'a> {
Bar(&'a mut bool),
Baz,
}
RunThis fails because &mut T
is not Copy
, even when T
is Copy
(this
differs from the behavior for &T
, which is always Copy
).
The Copy
trait was implemented on a type which is neither a struct nor an
enum.
Erroneous code example:
type Foo = [u8; 256];
impl Copy for Foo { } // error!
#[derive(Copy, Clone)]
struct Bar;
impl Copy for &'static mut Bar { } // error!
RunYou can only implement Copy
for a struct or an enum. Both of the previous
examples will fail, because neither [u8; 256]
nor &'static mut Bar
(mutable reference to Bar
) is a struct or enum.
A type parameter that is specified for impl
is not constrained.
Erroneous code example:
struct Foo;
impl<T: Default> Foo {
// error: the type parameter `T` is not constrained by the impl trait, self
// type, or predicates [E0207]
fn get(&self) -> T {
<T as Default>::default()
}
}
RunAny type parameter of an impl
must meet at least one of
the following criteria:
impl<T> Foo<T>
impl<T> SomeTrait<T> for Foo
impl<T, U> SomeTrait for T where T: AnotherTrait<AssocType=U>
Suppose we have a struct Foo
and we would like to define some methods for it.
The previous code example has a definition which leads to a compiler error:
The problem is that the parameter T
does not appear in the implementing type
(Foo
) of the impl. In this case, we can fix the error by moving the type
parameter from the impl
to the method get
:
struct Foo;
// Move the type parameter from the impl to the method
impl Foo {
fn get<T: Default>(&self) -> T {
<T as Default>::default()
}
}
RunAs another example, suppose we have a Maker
trait and want to establish a
type FooMaker
that makes Foo
s:
trait Maker {
type Item;
fn make(&mut self) -> Self::Item;
}
struct Foo<T> {
foo: T
}
struct FooMaker;
impl<T: Default> Maker for FooMaker {
// error: the type parameter `T` is not constrained by the impl trait, self
// type, or predicates [E0207]
type Item = Foo<T>;
fn make(&mut self) -> Foo<T> {
Foo { foo: <T as Default>::default() }
}
}
RunThis fails to compile because T
does not appear in the trait or in the
implementing type.
One way to work around this is to introduce a phantom type parameter into
FooMaker
, like so:
use std::marker::PhantomData;
trait Maker {
type Item;
fn make(&mut self) -> Self::Item;
}
struct Foo<T> {
foo: T
}
// Add a type parameter to `FooMaker`
struct FooMaker<T> {
phantom: PhantomData<T>,
}
impl<T: Default> Maker for FooMaker<T> {
type Item = Foo<T>;
fn make(&mut self) -> Foo<T> {
Foo {
foo: <T as Default>::default(),
}
}
}
RunAnother way is to do away with the associated type in Maker
and use an input
type parameter instead:
// Use a type parameter instead of an associated type here
trait Maker<Item> {
fn make(&mut self) -> Item;
}
struct Foo<T> {
foo: T
}
struct FooMaker;
impl<T: Default> Maker<Foo<T>> for FooMaker {
fn make(&mut self) -> Foo<T> {
Foo { foo: <T as Default>::default() }
}
}
RunFor more information, please see RFC 447.
No description.
This error indicates a violation of one of Rust’s orphan rules for trait implementations. The rule concerns the use of type parameters in an implementation of a foreign trait (a trait defined in another crate), and states that type parameters must be “covered” by a local type.
When implementing a foreign trait for a foreign type, the trait must have one or more type parameters. A type local to your crate must appear before any use of any type parameters.
To understand what this means, it is perhaps easier to consider a few examples.
If ForeignTrait
is a trait defined in some external crate foo
, then the
following trait impl
is an error:
extern crate foo;
use foo::ForeignTrait;
impl<T> ForeignTrait for T { } // error
RunTo work around this, it can be covered with a local type, MyType
:
struct MyType<T>(T);
impl<T> ForeignTrait for MyType<T> { } // Ok
RunPlease note that a type alias is not sufficient.
For another example of an error, suppose there’s another trait defined in foo
named ForeignTrait2
that takes two type parameters. Then this impl
results
in the same rule violation:
struct MyType2;
impl<T> ForeignTrait2<T, MyType<T>> for MyType2 { } // error
RunThe reason for this is that there are two appearances of type parameter T
in
the impl
header, both as parameters for ForeignTrait2
. The first appearance
is uncovered, and so runs afoul of the orphan rule.
Consider one more example:
impl<T> ForeignTrait2<MyType<T>, T> for MyType2 { } // Ok
RunThis only differs from the previous impl
in that the parameters T
and
MyType<T>
for ForeignTrait2
have been swapped. This example does not
violate the orphan rule; it is permitted.
To see why that last example was allowed, you need to understand the general
rule. Unfortunately this rule is a bit tricky to state. Consider an impl
:
impl<P1, ..., Pm> ForeignTrait<T1, ..., Tn> for T0 { ... }
Runwhere P1, ..., Pm
are the type parameters of the impl
and T0, ..., Tn
are types. One of the types T0, ..., Tn
must be a local type (this is another
orphan rule, see the explanation for E0117).
Both of the following must be true:
T0..=Tn
must be a local type.
Let Ti
be the first such type.P1..=Pm
may appear in T0..Ti
(excluding Ti
).For information on the design of the orphan rules, see RFC 2451 and RFC 1023.
For information on the design of the orphan rules, see RFC 1023.
You used a function or type which doesn’t fit the requirements for where it was used. Erroneous code examples:
#![feature(intrinsics)]
extern "rust-intrinsic" {
fn size_of<T>(); // error: intrinsic has wrong type
}
// or:
fn main() -> i32 { 0 }
// error: main function expects type: `fn() {main}`: expected (), found i32
// or:
let x = 1u8;
match x {
0u8..=3i8 => (),
// error: mismatched types in range: expected u8, found i8
_ => ()
}
// or:
use std::rc::Rc;
struct Foo;
impl Foo {
fn x(self: Rc<Foo>) {}
// error: mismatched self type: expected `Foo`: expected struct
// `Foo`, found struct `alloc::rc::Rc`
}
RunFor the first code example, please check the function definition. Example:
#![feature(intrinsics)]
extern "rust-intrinsic" {
fn size_of<T>() -> usize; // ok!
}
RunThe second case example is a bit particular: the main function must always have this definition:
fn main();
RunThey never take parameters and never return types.
For the third example, when you match, all patterns must have the same type as the type you’re matching on. Example:
let x = 1u8;
match x {
0u8..=3u8 => (), // ok!
_ => ()
}
RunAnd finally, for the last example, only Box<Self>
, &Self
, Self
,
or &mut Self
work as explicit self parameters. Example:
struct Foo;
impl Foo {
fn x(self: Box<Foo>) {} // ok!
}
RunCannot use the associated type of a trait with uninferred generic parameters.
Erroneous code example:
pub trait Foo<T> {
type A;
fn get(&self, t: T) -> Self::A;
}
fn foo2<I : for<'x> Foo<&'x isize>>(
field: I::A) {} // error!
RunIn this example, we have to instantiate 'x
, and
we don’t know what lifetime to instantiate it with.
To fix this, spell out the precise lifetimes involved.
Example:
pub trait Foo<T> {
type A;
fn get(&self, t: T) -> Self::A;
}
fn foo3<I : for<'x> Foo<&'x isize>>(
x: <I as Foo<&isize>>::A) {} // ok!
fn foo4<'a, I : for<'x> Foo<&'x isize>>(
x: <I as Foo<&'a isize>>::A) {} // ok!
RunA generic type was described using parentheses rather than angle brackets.
Erroneous code example:
let v: Vec(&str) = vec!["foo"];
RunThis is not currently supported: v
should be defined as Vec<&str>
.
Parentheses are currently only used with generic types when defining parameters
for Fn
-family traits.
The previous code example fixed:
let v: Vec<&str> = vec!["foo"];
RunThe associated type used was not defined in the trait.
Erroneous code example:
trait T1 {
type Bar;
}
type Foo = T1<F=i32>; // error: associated type `F` not found for `T1`
// or:
trait T2 {
type Bar;
// error: Baz is used but not declared
fn return_bool(&self, _: &Self::Bar, _: &Self::Baz) -> bool;
}
RunMake sure that you have defined the associated type in the trait body. Also, verify that you used the right trait or you didn’t misspell the associated type name. Example:
trait T1 {
type Bar;
}
type Foo = T1<Bar=i32>; // ok!
// or:
trait T2 {
type Bar;
type Baz; // we declare `Baz` in our trait.
// and now we can use it here:
fn return_bool(&self, _: &Self::Bar, _: &Self::Baz) -> bool;
}
RunAn attempt was made to retrieve an associated type, but the type was ambiguous.
Erroneous code example:
trait T1 {}
trait T2 {}
trait Foo {
type A: T1;
}
trait Bar : Foo {
type A: T2;
fn do_something() {
let _: Self::A;
}
}
RunIn this example, Foo
defines an associated type A
. Bar
inherits that type
from Foo
, and defines another associated type of the same name. As a result,
when we attempt to use Self::A
, it’s ambiguous whether we mean the A
defined
by Foo
or the one defined by Bar
.
There are two options to work around this issue. The first is simply to rename one of the types. Alternatively, one can specify the intended type using the following syntax:
trait T1 {}
trait T2 {}
trait Foo {
type A: T1;
}
trait Bar : Foo {
type A: T2;
fn do_something() {
let _: <Self as Bar>::A;
}
}
RunAn attempt was made to constrain an associated type.
Erroneous code example:
pub trait Vehicle {
type Color;
}
pub trait Box {
type Color;
}
pub trait BoxCar : Box + Vehicle {}
fn dent_object<COLOR>(c: dyn BoxCar<Color=COLOR>) {} // Invalid constraint
RunIn this example, BoxCar
has two supertraits: Vehicle
and Box
. Both of
these traits define an associated type Color
. BoxCar
inherits two types
with that name from both supertraits. Because of this, we need to use the
fully qualified path syntax to refer to the appropriate Color
associated
type, either <BoxCar as Vehicle>::Color
or <BoxCar as Box>::Color
, but this
syntax is not allowed to be used in a function signature.
In order to encode this kind of constraint, a where
clause and a new type
parameter are needed:
pub trait Vehicle {
type Color;
}
pub trait Box {
type Color;
}
pub trait BoxCar : Box + Vehicle {}
// Introduce a new `CAR` type parameter
fn foo<CAR, COLOR>(
c: CAR,
) where
// Bind the type parameter `CAR` to the trait `BoxCar`
CAR: BoxCar,
// Further restrict `<BoxCar as Vehicle>::Color` to be the same as the
// type parameter `COLOR`
CAR: Vehicle<Color = COLOR>,
// We can also simultaneously restrict the other trait's associated type
CAR: Box<Color = COLOR>
{}
RunAn attempt was made to retrieve an associated type, but the type was ambiguous.
Erroneous code example:
trait MyTrait {type X; }
fn main() {
let foo: MyTrait::X;
}
RunThe problem here is that we’re attempting to take the type of X from MyTrait. Unfortunately, the type of X is not defined, because it’s only made concrete in implementations of the trait. A working version of this code might look like:
trait MyTrait {type X; }
struct MyStruct;
impl MyTrait for MyStruct {
type X = u32;
}
fn main() {
let foo: <MyStruct as MyTrait>::X;
}
RunThis syntax specifies that we want the X type from MyTrait, as made concrete in
MyStruct. The reason that we cannot simply use MyStruct::X
is that MyStruct
might implement two different traits with identically-named associated types.
This syntax allows disambiguation between the two.
A trait object was declared with no traits.
Erroneous code example:
type Foo = dyn 'static +;
RunRust does not currently support this.
To solve, ensure that the trait object has at least one trait:
type Foo = dyn 'static + Copy;
RunMultiple types were used as bounds for a closure or trait object.
Erroneous code example:
fn main() {
let _: Box<dyn std::io::Read + std::io::Write>;
}
RunRust does not currently support this.
Auto traits such as Send and Sync are an exception to this rule: It’s possible to have bounds of one non-builtin trait, plus any number of auto traits. For example, the following compiles correctly:
fn main() {
let _: Box<dyn std::io::Read + Send + Sync>;
}
RunMore than one explicit lifetime bound was used on a trait object.
Example of erroneous code:
trait Foo {}
type T<'a, 'b> = dyn Foo + 'a + 'b; // error: Trait object `arg` has two
// lifetime bound, 'a and 'b.
RunHere T
is a trait object with two explicit lifetime bounds, ’a and ’b.
Only a single explicit lifetime bound is permitted on trait objects. To fix this error, consider removing one of the lifetime bounds:
trait Foo {}
type T<'a> = dyn Foo + 'a;
RunNo description.
The lifetime bound for this object type cannot be deduced from context and must be specified.
Erroneous code example:
trait Trait { }
struct TwoBounds<'a, 'b, T: Sized + 'a + 'b> {
x: &'a i32,
y: &'b i32,
z: T,
}
type Foo<'a, 'b> = TwoBounds<'a, 'b, dyn Trait>;
RunWhen a trait object is used as a type argument of a generic type, Rust will try to infer its lifetime if unspecified. However, this isn’t possible when the containing type has more than one lifetime bound.
The above example can be resolved by either reducing the number of lifetime bounds to one or by making the trait object lifetime explicit, like so:
trait Trait { }
struct TwoBounds<'a, 'b, T: Sized + 'a + 'b> {
x: &'a i32,
y: &'b i32,
z: T,
}
type Foo<'a, 'b> = TwoBounds<'a, 'b, dyn Trait + 'b>;
RunFor more information, see RFC 599 and its amendment RFC 1156.
An associated type binding was done outside of the type parameter declaration
and where
clause.
Erroneous code example:
pub trait Foo {
type A;
fn boo(&self) -> <Self as Foo>::A;
}
struct Bar;
impl Foo for isize {
type A = usize;
fn boo(&self) -> usize { 42 }
}
fn baz<I>(x: &<I as Foo<A=Bar>>::A) {}
// error: associated type bindings are not allowed here
RunTo solve this error, please move the type bindings in the type parameter declaration:
fn baz<I: Foo<A=Bar>>(x: &<I as Foo>::A) {} // ok!
RunOr in the where
clause:
fn baz<I>(x: &<I as Foo>::A) where I: Foo<A=Bar> {}
RunThe #[rustc_on_unimplemented]
attribute lets you specify a custom error
message for when a particular trait isn’t implemented on a type placed in a
position that needs that trait. For example, when the following code is
compiled:
#![feature(rustc_attrs)]
#[rustc_on_unimplemented = "error on `{Self}` with params `<{A},{B}>`"] // error
trait BadAnnotation<A> {}
RunThere will be an error about bool
not implementing Index<u8>
, followed by a
note saying “the type bool
cannot be indexed by u8
”.
As you can see, you can specify type parameters in curly braces for
substitution with the actual types (using the regular format string syntax) in
a given situation. Furthermore, {Self}
will substitute to the type (in this
case, bool
) that we tried to use.
This error appears when the curly braces contain an identifier which doesn’t
match with any of the type parameters or the string Self
. This might happen
if you misspelled a type parameter, or if you intended to use literal curly
braces. If it is the latter, escape the curly braces with a second curly brace
of the same type; e.g., a literal {
is {{
.
The #[rustc_on_unimplemented]
attribute lets you specify a custom error
message for when a particular trait isn’t implemented on a type placed in a
position that needs that trait. For example, when the following code is
compiled:
#![feature(rustc_attrs)]
#[rustc_on_unimplemented = "error on `{Self}` with params `<{A},{}>`"] // error!
trait BadAnnotation<A> {}
Runthere will be an error about bool
not implementing Index<u8>
, followed by a
note saying “the type bool
cannot be indexed by u8
”.
As you can see, you can specify type parameters in curly braces for
substitution with the actual types (using the regular format string syntax) in
a given situation. Furthermore, {Self}
will substitute to the type (in this
case, bool
) that we tried to use.
This error appears when the curly braces do not contain an identifier. Please
add one of the same name as a type parameter. If you intended to use literal
braces, use {{
and }}
to escape them.
The #[rustc_on_unimplemented]
attribute lets you specify a custom error
message for when a particular trait isn’t implemented on a type placed in a
position that needs that trait. For example, when the following code is
compiled:
#![feature(rustc_attrs)]
#[rustc_on_unimplemented(lorem="")] // error!
trait BadAnnotation {}
Runthere will be an error about bool
not implementing Index<u8>
, followed by a
note saying “the type bool
cannot be indexed by u8
”.
For this to work, some note must be specified. An empty attribute will not do anything, please remove the attribute or add some helpful note for users of the trait.
This error indicates that not enough type parameters were found in a type or trait.
For example, the Foo
struct below is defined to be generic in T
, but the
type parameter is missing in the definition of Bar
:
struct Foo<T> { x: T }
struct Bar { x: Foo }
RunThis error indicates that too many type parameters were found in a type or trait.
For example, the Foo
struct below has no type parameters, but is supplied
with two in the definition of Bar
:
struct Foo { x: bool }
struct Bar<S, T> { x: Foo<S, T> }
RunTwo items of the same name cannot be imported without rebinding one of the items under a new local name.
An example of this error:
use foo::baz;
use bar::*; // error, do `use foo::baz as quux` instead on the previous line
fn main() {}
mod foo {
pub struct baz;
}
mod bar {
pub mod baz {}
}
RunTwo items of the same name cannot be imported without rebinding one of the items under a new local name.
Erroneous code example:
use foo::baz;
use bar::baz; // error, do `use bar::baz as quux` instead
fn main() {}
mod foo {
pub struct baz;
}
mod bar {
pub mod baz {}
}
RunYou can use aliases in order to fix this error. Example:
use foo::baz as foo_baz;
use bar::baz; // ok!
fn main() {}
mod foo {
pub struct baz;
}
mod bar {
pub mod baz {}
}
RunOr you can reference the item with its parent:
use bar::baz;
fn main() {
let x = foo::baz; // ok!
}
mod foo {
pub struct baz;
}
mod bar {
pub mod baz {}
}
RunAttempt was made to import an unimportable value. This can happen when trying to import a method from a trait.
Erroneous code example:
mod foo {
pub trait MyTrait {
fn do_something();
}
}
use foo::MyTrait::do_something;
// error: `do_something` is not directly importable
fn main() {}
RunIt’s invalid to directly import methods belonging to a trait or concrete type.
Attempt was made to import an item whereas an extern crate with this name has already been imported.
Erroneous code example:
extern crate core;
mod foo {
pub trait core {
fn do_something();
}
}
use foo::core; // error: an extern crate named `core` has already
// been imported in this module
fn main() {}
RunTo fix this issue, you have to rename at least one of the two imports. Example:
extern crate core as libcore; // ok!
mod foo {
pub trait core {
fn do_something();
}
}
use foo::core;
fn main() {}
RunYou can’t import a value whose name is the same as another value defined in the module.
Erroneous code example:
use bar::foo; // error: an item named `foo` is already in scope
fn foo() {}
mod bar {
pub fn foo() {}
}
fn main() {}
RunYou can use aliases in order to fix this error. Example:
use bar::foo as bar_foo; // ok!
fn foo() {}
mod bar {
pub fn foo() {}
}
fn main() {}
RunOr you can reference the item with its parent:
fn foo() {}
mod bar {
pub fn foo() {}
}
fn main() {
bar::foo(); // we get the item by referring to its parent
}
RunYou can’t import a type or module when the name of the item being imported is the same as another type or submodule defined in the module.
An example of this error:
use foo::Bar; // error
type Bar = u32;
mod foo {
pub mod Bar { }
}
fn main() {}
RunThe name chosen for an external crate conflicts with another external crate that has been imported into the current module.
Erroneous code example:
extern crate core;
extern crate std as core;
fn main() {}
RunThe solution is to choose a different name that doesn’t conflict with any external crate imported into the current module.
Correct example:
extern crate core;
extern crate std as other_name;
fn main() {}
RunThe name for an item declaration conflicts with an external crate’s name.
Erroneous code example:
extern crate core;
struct core;
fn main() {}
RunThere are two possible solutions:
Solution #1: Rename the item.
extern crate core;
struct xyz;
RunSolution #2: Import the crate with a different name.
extern crate core as xyz;
struct abc;
RunSee the Declaration Statements section of the reference for more information about what constitutes an item declaration and what does not.
An undeclared lifetime was used.
Erroneous code example:
// error, use of undeclared lifetime name `'a`
fn foo(x: &'a str) { }
struct Foo {
// error, use of undeclared lifetime name `'a`
x: &'a str,
}
RunThese can be fixed by declaring lifetime parameters:
struct Foo<'a> {
x: &'a str,
}
fn foo<'a>(x: &'a str) {}
RunImpl blocks declare lifetime parameters separately. You need to add lifetime parameters to an impl block if you’re implementing a type that has a lifetime parameter of its own. For example:
struct Foo<'a> {
x: &'a str,
}
// error, use of undeclared lifetime name `'a`
impl Foo<'a> {
fn foo<'a>(x: &'a str) {}
}
RunThis is fixed by declaring the impl block like this:
struct Foo<'a> {
x: &'a str,
}
// correct
impl<'a> Foo<'a> {
fn foo(x: &'a str) {}
}
RunAn invalid name was used for a lifetime parameter.
Erroneous code example:
// error, invalid lifetime parameter name `'static`
fn foo<'static>(x: &'static str) { }
RunDeclaring certain lifetime names in parameters is disallowed. For example,
because the 'static
lifetime is a special built-in lifetime name denoting
the lifetime of the entire program, this is an error:
A lifetime was declared more than once in the same scope.
Erroneous code example:
fn foo<'a, 'b, 'a>(x: &'a str, y: &'b str, z: &'a str) { // error!
}
RunTwo lifetimes cannot have the same name. To fix this example, change
the second 'a
lifetime into something else ('c
for example):
fn foo<'a, 'b, 'c>(x: &'a str, y: &'b str, z: &'c str) { // ok!
}
RunAn unknown external lang item was used.
Erroneous code example:
#![feature(lang_items)]
extern "C" {
#[lang = "cake"] // error: unknown external lang item: `cake`
fn cake();
}
RunA list of available external lang items is available in
src/librustc_middle/middle/weak_lang_items.rs
. Example:
#![feature(lang_items)]
extern "C" {
#[lang = "panic_impl"] // ok!
fn cake();
}
RunA loop keyword (break
or continue
) was used inside a closure but outside of
any loop.
Erroneous code example:
let w = || { break; }; // error: `break` inside of a closure
Runbreak
and continue
keywords can be used as normal inside closures as long as
they are also contained within a loop. To halt the execution of a closure you
should instead use a return statement. Example:
let w = || {
for _ in 0..10 {
break;
}
};
w();
RunA loop keyword (break
or continue
) was used outside of a loop.
Erroneous code example:
fn some_func() {
break; // error: `break` outside of a loop
}
RunWithout a loop to break out of or continue in, no sensible action can be taken.
Please verify that you are using break
and continue
only in loops. Example:
fn some_func() {
for _ in 0..10 {
break; // ok!
}
}
RunA type mismatched an associated type of a trait.
Erroneous code example:
trait Trait { type AssociatedType; }
fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
// ~~~~~~~~ ~~~~~~~~~~~~~~~~~~
// | |
// This says `foo` can |
// only be used with |
// some type that |
// implements `Trait`. |
// |
// This says not only must
// `T` be an impl of `Trait`
// but also that the impl
// must assign the type `u32`
// to the associated type.
println!("in foo");
}
impl Trait for i8 { type AssociatedType = &'static str; }
//~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// | |
// `i8` does have |
// implementation |
// of `Trait`... |
// ... but it is an implementation
// that assigns `&'static str` to
// the associated type.
foo(3_i8);
// Here, we invoke `foo` with an `i8`, which does not satisfy
// the constraint `<i8 as Trait>::AssociatedType=u32`, and
// therefore the type-checker complains with this error code.
RunThe issue can be resolved by changing the associated type:
foo
implementation:trait Trait { type AssociatedType; }
fn foo<T>(t: T) where T: Trait<AssociatedType = &'static str> {
println!("in foo");
}
impl Trait for i8 { type AssociatedType = &'static str; }
foo(3_i8);
RunTrait
implementation for i8
:trait Trait { type AssociatedType; }
fn foo<T>(t: T) where T: Trait<AssociatedType = u32> {
println!("in foo");
}
impl Trait for i8 { type AssociatedType = u32; }
foo(3_i8);
RunAn evaluation of a trait requirement overflowed.
Erroneous code example:
trait Foo {}
struct Bar<T>(T);
impl<T> Foo for T where Bar<T>: Foo {}
RunThis error occurs when there was a recursive trait requirement that overflowed before it could be evaluated. This often means that there is an unbounded recursion in resolving some type bounds.
To determine if a T
is Foo
, we need to check if Bar<T>
is Foo
. However,
to do this check, we need to determine that Bar<Bar<T>>
is Foo
. To
determine this, we check if Bar<Bar<Bar<T>>>
is Foo
, and so on. This is
clearly a recursive requirement that can’t be resolved directly.
Consider changing your trait bounds so that they’re less self-referential.
A trait implementation has stricter requirements than the trait definition.
Erroneous code example:
trait Foo {
fn foo<T>(x: T);
}
impl Foo for bool {
fn foo<T>(x: T) where T: Copy {}
}
RunHere, all types implementing Foo
must have a method foo<T>(x: T)
which can
take any type T
. However, in the impl
for bool
, we have added an extra
bound that T
is Copy
, which isn’t compatible with the original trait.
Consider removing the bound from the method or adding the bound to the original method definition in the trait.
You tried to use a type which doesn’t implement some trait in a place which expected that trait.
Erroneous code example:
// here we declare the Foo trait with a bar method
trait Foo {
fn bar(&self);
}
// we now declare a function which takes an object implementing the Foo trait
fn some_func<T: Foo>(foo: T) {
foo.bar();
}
fn main() {
// we now call the method with the i32 type, which doesn't implement
// the Foo trait
some_func(5i32); // error: the trait bound `i32 : Foo` is not satisfied
}
RunIn order to fix this error, verify that the type you’re using does implement the trait. Example:
trait Foo {
fn bar(&self);
}
// we implement the trait on the i32 type
impl Foo for i32 {
fn bar(&self) {}
}
fn some_func<T: Foo>(foo: T) {
foo.bar(); // we can now use this method since i32 implements the
// Foo trait
}
fn main() {
some_func(5i32); // ok!
}
RunOr in a generic context, an erroneous code example would look like:
fn some_func<T>(foo: T) {
println!("{:?}", foo); // error: the trait `core::fmt::Debug` is not
// implemented for the type `T`
}
fn main() {
// We now call the method with the i32 type,
// which *does* implement the Debug trait.
some_func(5i32);
}
RunNote that the error here is in the definition of the generic function. Although
we only call it with a parameter that does implement Debug
, the compiler
still rejects the function. It must work with all possible input types. In
order to make this example compile, we need to restrict the generic type we’re
accepting:
use std::fmt;
// Restrict the input type to types that implement Debug.
fn some_func<T: fmt::Debug>(foo: T) {
println!("{:?}", foo);
}
fn main() {
// Calling the method is still fine, as i32 implements Debug.
some_func(5i32);
// This would fail to compile now:
// struct WithoutDebug;
// some_func(WithoutDebug);
}
RunRust only looks at the signature of the called function, as such it must already specify all requirements that will be used for every type parameter.
No description.
No description.
You tried to supply a type which doesn’t implement some trait in a location
which expected that trait. This error typically occurs when working with
Fn
-based types. Erroneous code example:
fn foo<F: Fn(usize)>(x: F) { }
fn main() {
// type mismatch: ... implements the trait `core::ops::Fn<(String,)>`,
// but the trait `core::ops::Fn<(usize,)>` is required
// [E0281]
foo(|y: String| { });
}
RunThe issue in this case is that foo
is defined as accepting a Fn
with one
argument of type String
, but the closure we attempted to pass to it requires
one arguments of type usize
.
The compiler could not infer a type and asked for a type annotation.
Erroneous code example:
let x = "hello".chars().rev().collect();
RunThis error indicates that type inference did not result in one unique possible type, and extra information is required. In most cases this can be provided by adding a type annotation. Sometimes you need to specify a generic type parameter manually.
A common example is the collect
method on Iterator
. It has a generic type
parameter with a FromIterator
bound, which for a char
iterator is
implemented by Vec
and String
among others. Consider the following snippet
that reverses the characters of a string:
In the first code example, the compiler cannot infer what the type of x
should
be: Vec<char>
and String
are both suitable candidates. To specify which type
to use, you can use a type annotation on x
:
let x: Vec<char> = "hello".chars().rev().collect();
RunIt is not necessary to annotate the full type. Once the ambiguity is resolved, the compiler can infer the rest:
let x: Vec<_> = "hello".chars().rev().collect();
RunAnother way to provide the compiler with enough information, is to specify the generic type parameter:
let x = "hello".chars().rev().collect::<Vec<char>>();
RunAgain, you need not specify the full type if the compiler can infer it:
let x = "hello".chars().rev().collect::<Vec<_>>();
RunApart from a method or function with a generic type parameter, this error can occur when a type parameter of a struct or trait cannot be inferred. In that case it is not always possible to use a type annotation, because all candidates have the same return type. For instance:
struct Foo<T> {
num: T,
}
impl<T> Foo<T> {
fn bar() -> i32 {
0
}
fn baz() {
let number = Foo::bar();
}
}
RunThis will fail because the compiler does not know which instance of Foo
to
call bar
on. Change Foo::bar()
to Foo::<T>::bar()
to resolve the error.
An implementation cannot be chosen unambiguously because of lack of information.
Erroneous code example:
trait Generator {
fn create() -> u32;
}
struct Impl;
impl Generator for Impl {
fn create() -> u32 { 1 }
}
struct AnotherImpl;
impl Generator for AnotherImpl {
fn create() -> u32 { 2 }
}
fn main() {
let cont: u32 = Generator::create();
// error, impossible to choose one of Generator trait implementation
// Should it be Impl or AnotherImpl, maybe something else?
}
RunThis error can be solved by adding type annotations that provide the missing information to the compiler. In this case, the solution is to use a concrete type:
trait Generator {
fn create() -> u32;
}
struct AnotherImpl;
impl Generator for AnotherImpl {
fn create() -> u32 { 2 }
}
fn main() {
let gen1 = AnotherImpl::create();
// if there are multiple methods with same name (different traits)
let gen2 = <AnotherImpl as Generator>::create();
}
RunThis error occurs when the compiler is unable to unambiguously infer the
return type of a function or method which is generic on return type, such
as the collect
method for Iterator
s.
For example:
fn main() {
let n: u32 = 1;
let mut d: u64 = 2;
d = d + n.into();
}
RunHere we have an addition of d
and n.into()
. Hence, n.into()
can return
any type T
where u64: Add<T>
. On the other hand, the into
method can
return any type where u32: Into<T>
.
The author of this code probably wants into()
to return a u64
, but the
compiler can’t be sure that there isn’t another type T
where both
u32: Into<T>
and u64: Add<T>
.
To resolve this error, use a concrete type for the intermediate expression:
fn main() {
let n: u32 = 1;
let mut d: u64 = 2;
let m: u64 = n.into();
d = d + m;
}
RunNote that the type of v
can now be inferred from the type of temp
.
Patterns used to bind names must be irrefutable. That is, they must guarantee
that a name will be extracted in all cases. Instead of pattern matching the
loop variable, consider using a match
or if let
inside the loop body. For
instance:
let xs : Vec<Option<i32>> = vec![Some(1), None];
// This fails because `None` is not covered.
for Some(x) in xs {
// ...
}
RunMatch inside the loop instead:
let xs : Vec<Option<i32>> = vec![Some(1), None];
for item in xs {
match item {
Some(x) => {},
None => {},
}
}
RunOr use if let
:
let xs : Vec<Option<i32>> = vec![Some(1), None];
for item in xs {
if let Some(x) = item {
// ...
}
}
RunMutable borrows are not allowed in pattern guards, because matching cannot have side effects. Side effects could alter the matched object or the environment on which the match depends in such a way, that the match would not be exhaustive. For instance, the following would not match any arm if mutable borrows were allowed:
match Some(()) {
None => { },
option if option.take().is_none() => {
/* impossible, option is `Some` */
},
Some(_) => { } // When the previous match failed, the option became `None`.
}
RunAssignments are not allowed in pattern guards, because matching cannot have side effects. Side effects could alter the matched object or the environment on which the match depends in such a way, that the match would not be exhaustive. For instance, the following would not match any arm if assignments were allowed:
match Some(()) {
None => { },
option if { option = None; false } => { },
Some(_) => { } // When the previous match failed, the option became `None`.
}
RunSub-bindings, e.g. ref x @ Some(ref y)
are now allowed under
#![feature(bindings_after_at)]
and checked to make sure that
memory safety is upheld.
In certain cases it is possible for sub-bindings to violate memory safety. Updates to the borrow checker in a future version of Rust may remove this restriction, but for now patterns must be rewritten without sub-bindings.
Before:
match Some("hi".to_string()) {
ref op_string_ref @ Some(s) => {},
None => {},
}
RunAfter:
match Some("hi".to_string()) {
Some(ref s) => {
let op_string_ref = &Some(s);
// ...
},
None => {},
}
RunThe op_string_ref
binding has type &Option<&String>
in both cases.
See also Issue 14587.
The self
parameter in a method has an invalid “receiver type”.
Erroneous code example:
struct Foo;
struct Bar;
trait Trait {
fn foo(&self);
}
impl Trait for Foo {
fn foo(self: &Bar) {}
}
RunMethods take a special first parameter, of which there are three variants:
self
, &self
, and &mut self
. These are syntactic sugar for
self: Self
, self: &Self
, and self: &mut Self
respectively.
trait Trait {
fn foo(&self);
// ^^^^^ `self` here is a reference to the receiver object
}
impl Trait for Foo {
fn foo(&self) {}
// ^^^^^ the receiver type is `&Foo`
}
RunThe type Self
acts as an alias to the type of the current trait
implementer, or “receiver type”. Besides the already mentioned Self
,
&Self
and &mut Self
valid receiver types, the following are also valid:
self: Box<Self>
, self: Rc<Self>
, self: Arc<Self>
, and self: Pin<P>
(where P is one of the previous types except Self
). Note that Self
can
also be the underlying implementing type, like Foo
in the following
example:
impl Trait for Foo {
fn foo(self: &Foo) {}
}
RunThis error will be emitted by the compiler when using an invalid receiver type, like in the following example:
impl Trait for Foo {
fn foo(self: &Bar) {}
}
RunThe nightly feature Arbitrary self types extends the accepted
set of receiver types to also include any type that can dereference to
Self
:
#![feature(arbitrary_self_types)]
struct Foo;
struct Bar;
// Because you can dereference `Bar` into `Foo`...
impl std::ops::Deref for Bar {
type Target = Foo;
fn deref(&self) -> &Foo {
&Foo
}
}
impl Foo {
fn foo(self: Bar) {}
// ^^^^^^^^^ ...it can be used as the receiver type
}
RunExpected type did not match the received type.
Erroneous code examples:
fn plus_one(x: i32) -> i32 {
x + 1
}
plus_one("Not a number");
// ^^^^^^^^^^^^^^ expected `i32`, found `&str`
if "Not a bool" {
// ^^^^^^^^^^^^ expected `bool`, found `&str`
}
let x: f32 = "Not a float";
// --- ^^^^^^^^^^^^^ expected `f32`, found `&str`
// |
// expected due to this
RunThis error occurs when an expression was used in a place where the compiler expected an expression of a different type. It can occur in several cases, the most common being when calling a function and passing an argument which has a different type than the matching type in the function declaration.
A parameter type is missing an explicit lifetime bound and may not live long enough.
Erroneous code example:
// This won't compile because the applicable impl of
// `SomeTrait` (below) requires that `T: 'a`, but the struct does
// not have a matching where-clause.
struct Foo<'a, T> {
foo: <T as SomeTrait<'a>>::Output,
}
trait SomeTrait<'a> {
type Output;
}
impl<'a, T> SomeTrait<'a> for T
where
T: 'a,
{
type Output = u32;
}
RunThe type definition contains some field whose type requires an outlives
annotation. Outlives annotations (e.g., T: 'a
) are used to guarantee that all
the data in T
is valid for at least the lifetime 'a
. This scenario most
commonly arises when the type contains an associated type reference like
<T as SomeTrait<'a>>::Output
, as shown in the previous code.
There, the where clause T: 'a
that appears on the impl is not known to be
satisfied on the struct. To make this example compile, you have to add a
where-clause like T: 'a
to the struct definition:
struct Foo<'a, T>
where
T: 'a,
{
foo: <T as SomeTrait<'a>>::Output
}
trait SomeTrait<'a> {
type Output;
}
impl<'a, T> SomeTrait<'a> for T
where
T: 'a,
{
type Output = u32;
}
RunA parameter type is missing a lifetime constraint or has a lifetime that does not live long enough.
Erroneous code example:
// This won't compile because T is not constrained to the static lifetime
// the reference needs
struct Foo<T> {
foo: &'static T
}
RunType parameters in type definitions have lifetimes associated with them that represent how long the data stored within them is guaranteed to live. This lifetime must be as long as the data needs to be alive, and missing the constraint that denotes this will cause this error.
This will compile, because it has the constraint on the type parameter:
struct Foo<T: 'static> {
foo: &'static T
}
RunNo description.
Reference’s lifetime of borrowed content doesn’t match the expected lifetime.
Erroneous code example:
pub fn opt_str<'a>(maybestr: &'a Option<String>) -> &'static str {
if maybestr.is_none() {
"(none)"
} else {
let s: &'a str = maybestr.as_ref().unwrap();
s // Invalid lifetime!
}
}
RunTo fix this error, either lessen the expected lifetime or find a way to not have to use this reference outside of its current scope (by running the code directly in the same block for example?):
// In this case, we can fix the issue by switching from "static" lifetime to 'a
pub fn opt_str<'a>(maybestr: &'a Option<String>) -> &'a str {
if maybestr.is_none() {
"(none)"
} else {
let s: &'a str = maybestr.as_ref().unwrap();
s // Ok!
}
}
RunNo description.
A where
clause contains a nested quantification over lifetimes.
Erroneous code example:
trait Tr<'a, 'b> {}
fn foo<T>(t: T)
where
for<'a> &'a T: for<'b> Tr<'a, 'b>, // error: nested quantification
{
}
RunRust syntax allows lifetime quantifications in two places within
where
clauses: Quantifying over the trait bound only (as in
Ty: for<'l> Trait<'l>
) and quantifying over the whole clause
(as in for<'l> &'l Ty: Trait<'l>
). Using both in the same clause
leads to a nested lifetime quantification, which is not supported.
The following example compiles, because the clause with the nested
quantification has been rewritten to use only one for<>
:
trait Tr<'a, 'b> {}
fn foo<T>(t: T)
where
for<'a, 'b> &'a T: Tr<'a, 'b>, // ok
{
}
RunAn if
expression is missing an else
block.
Erroneous code example:
let x = 5;
let a = if x == 5 {
1
};
RunThis error occurs when an if
expression without an else
block is used in a
context where a type other than ()
is expected. In the previous code example,
the let
expression was expecting a value but since there was no else
, no
value was returned.
An if
expression without an else
block has the type ()
, so this is a type
error. To resolve it, add an else
block having the same type as the if
block.
So to fix the previous code example:
let x = 5;
let a = if x == 5 {
1
} else {
2
};
RunNo description.
A cross-crate opt-out trait was implemented on something which wasn’t a struct or enum type.
Erroneous code example:
#![feature(auto_traits)]
struct Foo;
impl !Sync for Foo {}
unsafe impl Send for &'static Foo {}
// error: cross-crate traits with a default impl, like `core::marker::Send`,
// can only be implemented for a struct/enum type, not
// `&'static Foo`
RunOnly structs and enums are permitted to impl Send, Sync, and other opt-out
trait, and the struct or enum must be local to the current crate. So, for
example, unsafe impl Send for Rc<Foo>
is not allowed.
The Sized
trait was implemented explicitly.
Erroneous code example:
struct Foo;
impl Sized for Foo {} // error!
RunThe Sized
trait is a special trait built-in to the compiler for types with a
constant size known at compile-time. This trait is automatically implemented
for types as needed by the compiler, and it is currently disallowed to
explicitly implement it for a type.
An associated const was implemented when another trait item was expected.
Erroneous code example:
trait Foo {
type N;
}
struct Bar;
impl Foo for Bar {
const N : u32 = 0;
// error: item `N` is an associated const, which doesn't match its
// trait `<Bar as Foo>`
}
RunPlease verify that the associated const wasn’t misspelled and the correct trait was implemented. Example:
struct Bar;
trait Foo {
type N;
}
impl Foo for Bar {
type N = u32; // ok!
}
RunOr:
struct Bar;
trait Foo {
const N : u32;
}
impl Foo for Bar {
const N : u32 = 0; // ok!
}
RunA method was implemented when another trait item was expected.
Erroneous code example:
struct Bar;
trait Foo {
const N : u32;
fn M();
}
impl Foo for Bar {
fn N() {}
// error: item `N` is an associated method, which doesn't match its
// trait `<Bar as Foo>`
}
RunTo fix this error, please verify that the method name wasn’t misspelled and verify that you are indeed implementing the correct trait items. Example:
struct Bar;
trait Foo {
const N : u32;
fn M();
}
impl Foo for Bar {
const N : u32 = 0;
fn M() {} // ok!
}
RunAn associated type was implemented when another trait item was expected.
Erroneous code example:
struct Bar;
trait Foo {
const N : u32;
}
impl Foo for Bar {
type N = u32;
// error: item `N` is an associated type, which doesn't match its
// trait `<Bar as Foo>`
}
RunPlease verify that the associated type name wasn’t misspelled and your implementation corresponds to the trait definition. Example:
struct Bar;
trait Foo {
type N;
}
impl Foo for Bar {
type N = u32; // ok!
}
RunOr:
struct Bar;
trait Foo {
const N : u32;
}
impl Foo for Bar {
const N : u32 = 0; // ok!
}
RunAn implementation of a trait doesn’t match the type constraint.
Erroneous code example:
trait Foo {
const BAR: bool;
}
struct Bar;
impl Foo for Bar {
const BAR: u32 = 5; // error, expected bool, found u32
}
RunThe types of any associated constants in a trait implementation must match the types in the trait definition.
The Unsize trait should not be implemented directly. All implementations of Unsize are provided automatically by the compiler.
Erroneous code example:
#![feature(unsize)]
use std::marker::Unsize;
pub struct MyType;
impl<T> Unsize<T> for MyType {}
RunIf you are defining your own smart pointer type and would like to enable
conversion from a sized to an unsized type with the
DST coercion system, use CoerceUnsized
instead.
#![feature(coerce_unsized)]
use std::ops::CoerceUnsized;
pub struct MyType<T: ?Sized> {
field_with_unsized_type: T,
}
impl<T, U> CoerceUnsized<MyType<U>> for MyType<T>
where T: CoerceUnsized<U> {}
RunAn attempt was made to access an associated constant through either a generic
type parameter or Self
. This is not supported yet. An example causing this
error is shown below:
trait Foo {
const BAR: f64;
}
struct MyStruct;
impl Foo for MyStruct {
const BAR: f64 = 0f64;
}
fn get_bar_bad<F: Foo>(t: F) -> f64 {
F::BAR
}
RunCurrently, the value of BAR
for a particular type can only be accessed
through a concrete type, as shown below:
trait Foo {
const BAR: f64;
}
struct MyStruct;
impl Foo for MyStruct {
const BAR: f64 = 0f64;
}
fn get_bar_good() -> f64 {
<MyStruct as Foo>::BAR
}
RunPrivate items cannot be publicly re-exported. This error indicates that you
attempted to pub use
a type or value that was not itself public.
Erroneous code example:
mod a {
fn foo() {}
mod a {
pub use super::foo; // error!
}
}
RunThe solution to this problem is to ensure that the items that you are
re-exporting are themselves marked with pub
:
mod a {
pub fn foo() {} // ok!
mod a {
pub use super::foo;
}
}
RunSee the Use Declarations section of the reference for more information on this topic.
Private modules cannot be publicly re-exported. This error indicates that you
attempted to pub use
a module that was not itself public.
Erroneous code example:
mod foo {
pub const X: u32 = 1;
}
pub use foo as foo2;
fn main() {}
RunThe solution to this problem is to ensure that the module that you are
re-exporting is itself marked with pub
:
pub mod foo {
pub const X: u32 = 1;
}
pub use foo as foo2;
fn main() {}
RunSee the Use Declarations section of the reference for more information on this topic.
An attempt was made to implement Drop
on a concrete specialization of a
generic type. An example is shown below:
struct Foo<T> {
t: T
}
impl Drop for Foo<u32> {
fn drop(&mut self) {}
}
RunThis code is not legal: it is not possible to specialize Drop
to a subset of
implementations of a generic type. One workaround for this is to wrap the
generic type, as shown below:
struct Foo<T> {
t: T
}
struct Bar {
t: Foo<u32>
}
impl Drop for Bar {
fn drop(&mut self) {}
}
RunAn attempt was made to implement Drop
on a specialization of a generic type.
Erroneous code example:
trait Foo {}
struct MyStruct<T> {
t: T
}
impl<T: Foo> Drop for MyStruct<T> {
fn drop(&mut self) {}
}
RunThis code is not legal: it is not possible to specialize Drop
to a subset of
implementations of a generic type. In order for this code to work, MyStruct
must also require that T
implements Foo
. Alternatively, another option is
to wrap the generic type in another that specializes appropriately:
trait Foo{}
struct MyStruct<T> {
t: T
}
struct MyStructWrapper<T: Foo> {
t: MyStruct<T>
}
impl <T: Foo> Drop for MyStructWrapper<T> {
fn drop(&mut self) {}
}
RunA binary assignment operator like +=
or ^=
was applied to a type that
doesn’t support it.
Erroneous code example:
let mut x = 12f32; // error: binary operation `<<` cannot be applied to
// type `f32`
x <<= 2;
RunTo fix this error, please check that this type implements this binary operation. Example:
let mut x = 12u32; // the `u32` type does implement the `ShlAssign` trait
x <<= 2; // ok!
RunIt is also possible to overload most operators for your own type by
implementing the [OP]Assign
traits from std::ops
.
Another problem you might be facing is this: suppose you’ve overloaded the +
operator for some type Foo
by implementing the std::ops::Add
trait for
Foo
, but you find that using +=
does not work, as in this example:
use std::ops::Add;
struct Foo(u32);
impl Add for Foo {
type Output = Foo;
fn add(self, rhs: Foo) -> Foo {
Foo(self.0 + rhs.0)
}
}
fn main() {
let mut x: Foo = Foo(5);
x += Foo(7); // error, `+= cannot be applied to the type `Foo`
}
RunThis is because AddAssign
is not automatically implemented, so you need to
manually implement it for your type.
A binary operation was attempted on a type which doesn’t support it.
Erroneous code example:
let x = 12f32; // error: binary operation `<<` cannot be applied to
// type `f32`
x << 2;
RunTo fix this error, please check that this type implements this binary operation. Example:
let x = 12u32; // the `u32` type does implement it:
// https://doc.rust-lang.org/stable/std/ops/trait.Shl.html
x << 2; // ok!
RunIt is also possible to overload most operators for your own type by
implementing traits from std::ops
.
String concatenation appends the string on the right to the string on the
left and may require reallocation. This requires ownership of the string
on the left. If something should be added to a string literal, move the
literal to the heap by allocating it with to_owned()
like in
"Your text".to_owned()
.
The maximum value of an enum was reached, so it cannot be automatically set in the next enum value.
Erroneous code example:
#[repr(i64)]
enum Foo {
X = 0x7fffffffffffffff,
Y, // error: enum discriminant overflowed on value after
// 9223372036854775807: i64; set explicitly via
// Y = -9223372036854775808 if that is desired outcome
}
RunTo fix this, please set manually the next enum value or put the enum variant with the maximum value at the end of the enum. Examples:
#[repr(i64)]
enum Foo {
X = 0x7fffffffffffffff,
Y = 0, // ok!
}
RunOr:
#[repr(i64)]
enum Foo {
Y = 0, // ok!
X = 0x7fffffffffffffff,
}
RunA trait was implemented on another which already automatically implemented it.
Erroneous code examples:
trait Foo { fn foo(&self) { } }
trait Bar: Foo { }
trait Baz: Bar { }
impl Bar for Baz { } // error, `Baz` implements `Bar` by definition
impl Foo for Baz { } // error, `Baz` implements `Bar` which implements `Foo`
impl Baz for Baz { } // error, `Baz` (trivially) implements `Baz`
impl Baz for Bar { } // Note: This is OK
RunWhen Trait2
is a subtrait of Trait1
(for example, when Trait2
has a
definition like trait Trait2: Trait1 { ... }
), it is not allowed to implement
Trait1
for Trait2
. This is because Trait2
already implements Trait1
by
definition, so it is not useful to do this.
A captured variable in a closure may not live long enough.
Erroneous code example:
fn foo() -> Box<Fn(u32) -> u32> {
let x = 0u32;
Box::new(|y| x + y)
}
RunThis error occurs when an attempt is made to use data captured by a closure, when that data may no longer exist. It’s most commonly seen when attempting to return a closure as shown in the previous code example.
Notice that x
is stack-allocated by foo()
. By default, Rust captures
closed-over data by reference. This means that once foo()
returns, x
no
longer exists. An attempt to access x
within the closure would thus be
unsafe.
Another situation where this might be encountered is when spawning threads:
fn foo() {
let x = 0u32;
let y = 1u32;
let thr = std::thread::spawn(|| {
x + y
});
}
RunSince our new thread runs in parallel, the stack frame containing x
and y
may well have disappeared by the time we try to use them. Even if we call
thr.join()
within foo (which blocks until thr
has completed, ensuring the
stack frame won’t disappear), we will not succeed: the compiler cannot prove
that this behavior is safe, and so won’t let us do it.
The solution to this problem is usually to switch to using a move
closure.
This approach moves (or copies, where possible) data into the closure, rather
than taking references to it. For example:
fn foo() -> Box<Fn(u32) -> u32> {
let x = 0u32;
Box::new(move |y| x + y)
}
RunNow that the closure has its own copy of the data, there’s no need to worry about safety.
This error may also be encountered while using async
blocks:
use std::future::Future;
async fn f() {
let v = vec![1, 2, 3i32];
spawn(async { //~ ERROR E0373
println!("{:?}", v)
});
}
fn spawn<F: Future + Send + 'static>(future: F) {
unimplemented!()
}
RunSimilarly to closures, async
blocks are not executed immediately and may
capture closed-over data by reference. For more information, see
https://rust-lang.github.io/async-book/03_async_await/01_chapter.html.
CoerceUnsized
was implemented on a struct which does not contain a field with
an unsized type.
Example of erroneous code:
#![feature(coerce_unsized)]
use std::ops::CoerceUnsized;
struct Foo<T: ?Sized> {
a: i32,
}
// error: Struct `Foo` has no unsized fields that need `CoerceUnsized`.
impl<T, U> CoerceUnsized<Foo<U>> for Foo<T>
where T: CoerceUnsized<U> {}
RunAn unsized type is any type where the compiler does not know the length or alignment of at compile time. Any struct containing an unsized type is also unsized.
CoerceUnsized
is used to coerce one struct containing an unsized type
into another struct containing a different unsized type. If the struct
doesn’t have any fields of unsized types then you don’t need explicit
coercion to get the types you want. To fix this you can either
not try to implement CoerceUnsized
or you can add a field that is
unsized to the struct.
Example:
#![feature(coerce_unsized)]
use std::ops::CoerceUnsized;
// We don't need to impl `CoerceUnsized` here.
struct Foo {
a: i32,
}
// We add the unsized type field to the struct.
struct Bar<T: ?Sized> {
a: i32,
b: T,
}
// The struct has an unsized field so we can implement
// `CoerceUnsized` for it.
impl<T, U> CoerceUnsized<Bar<U>> for Bar<T>
where T: CoerceUnsized<U> {}
RunNote that CoerceUnsized
is mainly used by smart pointers like Box
, Rc
and Arc
to be able to mark that they can coerce unsized types that they
are pointing at.
CoerceUnsized
was implemented on a struct which contains more than one field
with an unsized type.
Erroneous code example:
#![feature(coerce_unsized)]
use std::ops::CoerceUnsized;
struct Foo<T: ?Sized, U: ?Sized> {
a: i32,
b: T,
c: U,
}
// error: Struct `Foo` has more than one unsized field.
impl<T, U> CoerceUnsized<Foo<U, T>> for Foo<T, U> {}
RunA struct with more than one field containing an unsized type cannot implement
CoerceUnsized
. This only occurs when you are trying to coerce one of the
types in your struct to another type in the struct. In this case we try to
impl CoerceUnsized
from T
to U
which are both types that the struct
takes. An unsized type is any type that the compiler doesn’t know the
length or alignment of at compile time. Any struct containing an unsized type
is also unsized.
CoerceUnsized
only allows for coercion from a structure with a single
unsized type field to another struct with a single unsized type field.
In fact Rust only allows for a struct to have one unsized type in a struct
and that unsized type must be the last field in the struct. So having two
unsized types in a single struct is not allowed by the compiler. To fix this
use only one field containing an unsized type in the struct and then use
multiple structs to manage each unsized type field you need.
Example:
#![feature(coerce_unsized)]
use std::ops::CoerceUnsized;
struct Foo<T: ?Sized> {
a: i32,
b: T,
}
impl <T, U> CoerceUnsized<Foo<U>> for Foo<T>
where T: CoerceUnsized<U> {}
fn coerce_foo<T: CoerceUnsized<U>, U>(t: T) -> Foo<U> {
Foo { a: 12i32, b: t } // we use coercion to get the `Foo<U>` type we need
}
RunCoerceUnsized
was implemented on something that isn’t a struct.
Erroneous code example:
#![feature(coerce_unsized)]
use std::ops::CoerceUnsized;
struct Foo<T: ?Sized> {
a: T,
}
// error: The type `U` is not a struct
impl<T, U> CoerceUnsized<U> for Foo<T> {}
RunCoerceUnsized
can only be implemented for a struct. Unsized types are
already able to be coerced without an implementation of CoerceUnsized
whereas a struct containing an unsized type needs to know the unsized type
field it’s containing is able to be coerced. An unsized type
is any type that the compiler doesn’t know the length or alignment of at
compile time. Any struct containing an unsized type is also unsized.
The CoerceUnsized
trait takes a struct type. Make sure the type you are
providing to CoerceUnsized
is a struct with only the last field containing an
unsized type.
Example:
#![feature(coerce_unsized)]
use std::ops::CoerceUnsized;
struct Foo<T> {
a: T,
}
// The `Foo<U>` is a struct so `CoerceUnsized` can be implemented
impl<T, U> CoerceUnsized<Foo<U>> for Foo<T> where T: CoerceUnsized<U> {}
RunNote that in Rust, structs can only contain an unsized type if the field containing the unsized type is the last and only unsized type field in the struct.
No description.
The DispatchFromDyn
trait was implemented on something which is not a pointer
or a newtype wrapper around a pointer.
Erroneous code example:
#![feature(dispatch_from_dyn)]
use std::ops::DispatchFromDyn;
struct WrapperExtraField<T> {
ptr: T,
extra_stuff: i32,
}
impl<T, U> DispatchFromDyn<WrapperExtraField<U>> for WrapperExtraField<T>
where
T: DispatchFromDyn<U>,
{}
RunThe DispatchFromDyn
trait currently can only be implemented for
builtin pointer types and structs that are newtype wrappers around them
— that is, the struct must have only one field (except forPhantomData
),
and that field must itself implement DispatchFromDyn
.
#![feature(dispatch_from_dyn, unsize)]
use std::{
marker::Unsize,
ops::DispatchFromDyn,
};
struct Ptr<T: ?Sized>(*const T);
impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Ptr<U>> for Ptr<T>
where
T: Unsize<U>,
{}
RunAnother example:
#![feature(dispatch_from_dyn)]
use std::{
ops::DispatchFromDyn,
marker::PhantomData,
};
struct Wrapper<T> {
ptr: T,
_phantom: PhantomData<()>,
}
impl<T, U> DispatchFromDyn<Wrapper<U>> for Wrapper<T>
where
T: DispatchFromDyn<U>,
{}
RunA trait method was declared const.
Erroneous code example:
trait Foo {
const fn bar() -> u32; // error!
}
RunTrait methods cannot be declared const
by design. For more information, see
RFC 911.
An auto trait was declared with a method or an associated item.
Erroneous code example:
unsafe auto trait Trait {
type Output; // error!
}
RunAuto traits cannot have methods or associated items. For more information see the opt-in builtin traits RFC.
It is not allowed to use or capture an uninitialized variable.
Erroneous code example:
fn main() {
let x: i32;
let y = x; // error, use of possibly-uninitialized variable
}
RunTo fix this, ensure that any declared variables are initialized before being used. Example:
fn main() {
let x: i32 = 0;
let y = x; // ok!
}
RunA variable was used after its contents have been moved elsewhere.
Erroneous code example:
struct MyStruct { s: u32 }
fn main() {
let mut x = MyStruct{ s: 5u32 };
let y = x;
x.s = 6;
println!("{}", x.s);
}
RunSince MyStruct
is a type that is not marked Copy
, the data gets moved out
of x
when we set y
. This is fundamental to Rust’s ownership system: outside
of workarounds like Rc
, a value cannot be owned by more than one variable.
Sometimes we don’t need to move the value. Using a reference, we can let another
function borrow the value without changing its ownership. In the example below,
we don’t actually have to move our string to calculate_length
, we can give it
a reference to it with &
instead.
fn main() {
let s1 = String::from("hello");
let len = calculate_length(&s1);
println!("The length of '{}' is {}.", s1, len);
}
fn calculate_length(s: &String) -> usize {
s.len()
}
RunA mutable reference can be created with &mut
.
Sometimes we don’t want a reference, but a duplicate. All types marked Clone
can be duplicated by calling .clone()
. Subsequent changes to a clone do not
affect the original variable.
Most types in the standard library are marked Clone
. The example below
demonstrates using clone()
on a string. s1
is first set to “many”, and then
copied to s2
. Then the first character of s1
is removed, without affecting
s2
. “any many” is printed to the console.
fn main() {
let mut s1 = String::from("many");
let s2 = s1.clone();
s1.remove(0);
println!("{} {}", s1, s2);
}
RunIf we control the definition of a type, we can implement Clone
on it ourselves
with #[derive(Clone)]
.
Some types have no ownership semantics at all and are trivial to duplicate. An
example is i32
and the other number types. We don’t have to call .clone()
to
clone them, because they are marked Copy
in addition to Clone
. Implicit
cloning is more convenient in this case. We can mark our own types Copy
if
all their members also are marked Copy
.
In the example below, we implement a Point
type. Because it only stores two
integers, we opt-out of ownership semantics with Copy
. Then we can
let p2 = p1
without p1
being moved.
#[derive(Copy, Clone)]
struct Point { x: i32, y: i32 }
fn main() {
let mut p1 = Point{ x: -1, y: 2 };
let p2 = p1;
p1.x = 1;
println!("p1: {}, {}", p1.x, p1.y);
println!("p2: {}, {}", p2.x, p2.y);
}
RunAlternatively, if we don’t control the struct’s definition, or mutable shared
ownership is truly required, we can use Rc
and RefCell
:
use std::cell::RefCell;
use std::rc::Rc;
struct MyStruct { s: u32 }
fn main() {
let mut x = Rc::new(RefCell::new(MyStruct{ s: 5u32 }));
let y = x.clone();
x.borrow_mut().s = 6;
println!("{}", x.borrow().s);
}
RunWith this approach, x and y share ownership of the data via the Rc
(reference
count type). RefCell
essentially performs runtime borrow checking: ensuring
that at most one writer or multiple readers can access the data at any one time.
If you wish to learn more about ownership in Rust, start with the Understanding Ownership chapter in the Book.
This error occurs when an attempt is made to partially reinitialize a structure that is currently uninitialized.
For example, this can happen when a drop has taken place:
struct Foo {
a: u32,
}
impl Drop for Foo {
fn drop(&mut self) { /* ... */ }
}
let mut x = Foo { a: 1 };
drop(x); // `x` is now uninitialized
x.a = 2; // error, partial reinitialization of uninitialized structure `t`
RunThis error can be fixed by fully reinitializing the structure in question:
struct Foo {
a: u32,
}
impl Drop for Foo {
fn drop(&mut self) { /* ... */ }
}
let mut x = Foo { a: 1 };
drop(x);
x = Foo { a: 2 };
RunAn immutable variable was reassigned.
Erroneous code example:
fn main() {
let x = 3;
x = 5; // error, reassignment of immutable variable
}
RunBy default, variables in Rust are immutable. To fix this error, add the keyword
mut
after the keyword let
when declaring the variable. For example:
fn main() {
let mut x = 3;
x = 5;
}
RunThis error occurs when an attempt is made to mutate the target of a mutable reference stored inside an immutable container.
For example, this can happen when storing a &mut
inside an immutable Box
:
let mut x: i64 = 1;
let y: Box<_> = Box::new(&mut x);
**y = 2; // error, cannot assign to data in an immutable container
RunThis error can be fixed by making the container mutable:
let mut x: i64 = 1;
let mut y: Box<_> = Box::new(&mut x);
**y = 2;
RunIt can also be fixed by using a type with interior mutability, such as Cell
or RefCell
:
use std::cell::Cell;
let x: i64 = 1;
let y: Box<Cell<_>> = Box::new(Cell::new(x));
y.set(2);
RunThis error occurs when an attempt is made to mutate or mutably reference data that a closure has captured immutably.
Erroneous code example:
// Accepts a function or a closure that captures its environment immutably.
// Closures passed to foo will not be able to mutate their closed-over state.
fn foo<F: Fn()>(f: F) { }
// Attempts to mutate closed-over data. Error message reads:
// `cannot assign to data in a captured outer variable...`
fn mutable() {
let mut x = 0u32;
foo(|| x = 2);
}
// Attempts to take a mutable reference to closed-over data. Error message
// reads: `cannot borrow data mutably in a captured outer variable...`
fn mut_addr() {
let mut x = 0u32;
foo(|| { let y = &mut x; });
}
RunThe problem here is that foo is defined as accepting a parameter of type Fn
.
Closures passed into foo will thus be inferred to be of type Fn
, meaning that
they capture their context immutably.
If the definition of foo
is under your control, the simplest solution is to
capture the data mutably. This can be done by defining foo
to take FnMut
rather than Fn:
fn foo<F: FnMut()>(f: F) { }
RunAlternatively, we can consider using the Cell
and RefCell
types to achieve
interior mutability through a shared reference. Our example’s mutable
function could be redefined as below:
use std::cell::Cell;
fn foo<F: Fn()>(f: F) { }
fn mutable() {
let x = Cell::new(0u32);
foo(|| x.set(2));
}
RunYou can read more in the API documentation for Cell.
An attempt was made to mutate data using a non-mutable reference. This
commonly occurs when attempting to assign to a non-mutable reference of a
mutable reference (&(&mut T)
).
Erroneous code example:
struct FancyNum {
num: u8,
}
fn main() {
let mut fancy = FancyNum{ num: 5 };
let fancy_ref = &(&mut fancy);
fancy_ref.num = 6; // error: cannot assign to data in a `&` reference
println!("{}", fancy_ref.num);
}
RunHere, &mut fancy
is mutable, but &(&mut fancy)
is not. Creating an
immutable reference to a value borrows it immutably. There can be multiple
references of type &(&mut T)
that point to the same value, so they must be
immutable to prevent multiple mutable references to the same value.
To fix this, either remove the outer reference:
struct FancyNum {
num: u8,
}
fn main() {
let mut fancy = FancyNum{ num: 5 };
let fancy_ref = &mut fancy;
// `fancy_ref` is now &mut FancyNum, rather than &(&mut FancyNum)
fancy_ref.num = 6; // No error!
println!("{}", fancy_ref.num);
}
RunOr make the outer reference mutable:
struct FancyNum {
num: u8
}
fn main() {
let mut fancy = FancyNum{ num: 5 };
let fancy_ref = &mut (&mut fancy);
// `fancy_ref` is now &mut(&mut FancyNum), rather than &(&mut FancyNum)
fancy_ref.num = 6; // No error!
println!("{}", fancy_ref.num);
}
RunA method or constant was implemented on a primitive type.
Erroneous code example:
struct Foo {
x: i32
}
impl *mut Foo {}
// error: only a single inherent implementation marked with
// `#[lang = "mut_ptr"]` is allowed for the `*mut T` primitive
RunThis isn’t allowed, but using a trait to implement a method or constant is a good solution. Example:
struct Foo {
x: i32
}
trait Bar {
fn bar();
}
impl Bar for *mut Foo {
fn bar() {} // ok!
}
RunA type dependency cycle has been encountered.
Erroneous code example:
trait FirstTrait : SecondTrait {
}
trait SecondTrait : FirstTrait {
}
RunThe previous example contains a circular dependency between two traits:
FirstTrait
depends on SecondTrait
which itself depends on FirstTrait
.
A type or lifetime parameter has been declared but is not actually used.
Erroneous code example:
enum Foo<T> {
Bar,
}
RunIf the type parameter was included by mistake, this error can be fixed by simply removing the type parameter, as shown below:
enum Foo {
Bar,
}
RunAlternatively, if the type parameter was intentionally inserted, it must be used. A simple fix is shown below:
enum Foo<T> {
Bar(T),
}
RunThis error may also commonly be found when working with unsafe code. For example, when using raw pointers one may wish to specify the lifetime for which the pointed-at data is valid. An initial attempt (below) causes this error:
struct Foo<'a, T> {
x: *const T,
}
RunWe want to express the constraint that Foo should not outlive 'a
, because
the data pointed to by T
is only valid for that lifetime. The problem is
that there are no actual uses of 'a
. It’s possible to work around this
by adding a PhantomData type to the struct, using it to tell the compiler
to act as if the struct contained a borrowed reference &'a T
:
use std::marker::PhantomData;
struct Foo<'a, T: 'a> {
x: *const T,
phantom: PhantomData<&'a T>
}
RunPhantomData can also be used to express information about unused type parameters.
A type parameter which references Self
in its default value was not specified.
Erroneous code example:
trait A<T=Self> {}
fn together_we_will_rule_the_galaxy(son: &A) {}
// error: the type parameter `T` must be explicitly specified in an
// object type because its default value `Self` references the
// type `Self`
RunA trait object is defined over a single, fully-defined trait. With a regular
default parameter, this parameter can just be substituted in. However, if the
default parameter is Self
, the trait changes for each concrete type; i.e.
i32
will be expected to implement A<i32>
, bool
will be expected to
implement A<bool>
, etc… These types will not share an implementation of a
fully-defined trait; instead they share implementations of a trait with
different parameters substituted in for each implementation. This is
irreconcilable with what we need to make a trait object work, and is thus
disallowed. Making the trait concrete by explicitly specifying the value of the
defaulted parameter will fix this issue. Fixed example:
trait A<T=Self> {}
fn together_we_will_rule_the_galaxy(son: &A<i32>) {} // Ok!
RunIn Rust 1.3, the default object lifetime bounds are expected to change, as described in RFC 1156. You are getting a warning because the compiler thinks it is possible that this change will cause a compilation error in your code. It is possible, though unlikely, that this is a false alarm.
The heart of the change is that where &'a Box<SomeTrait>
used to default to
&'a Box<SomeTrait+'a>
, it now defaults to &'a Box<SomeTrait+'static>
(here,
SomeTrait
is the name of some trait type). Note that the only types which are
affected are references to boxes, like &Box<SomeTrait>
or
&[Box<SomeTrait>]
. More common types like &SomeTrait
or Box<SomeTrait>
are unaffected.
To silence this warning, edit your code to use an explicit bound. Most of the
time, this means that you will want to change the signature of a function that
you are calling. For example, if the error is reported on a call like foo(x)
,
and foo
is defined as follows:
fn foo(arg: &Box<SomeTrait>) { /* ... */ }
RunYou might change it to:
fn foo<'a>(arg: &'a Box<SomeTrait+'a>) { /* ... */ }
RunThis explicitly states that you expect the trait object SomeTrait
to contain
references (with a maximum lifetime of 'a
).
You implemented a trait, overriding one or more of its associated types but did not reimplement its default methods.
Example of erroneous code:
#![feature(associated_type_defaults)]
pub trait Foo {
type Assoc = u8;
fn bar(&self) {}
}
impl Foo for i32 {
// error - the following trait items need to be reimplemented as
// `Assoc` was overridden: `bar`
type Assoc = i32;
}
RunTo fix this, add an implementation for each default method from the trait:
#![feature(associated_type_defaults)]
pub trait Foo {
type Assoc = u8;
fn bar(&self) {}
}
impl Foo for i32 {
type Assoc = i32;
fn bar(&self) {} // ok!
}
RunInner items do not inherit type or const parameters from the functions they are embedded in.
Erroneous code example:
fn foo<T>(x: T) {
fn bar(y: T) { // T is defined in the "outer" function
// ..
}
bar(x);
}
RunNor will this:
fn foo<T>(x: T) {
type MaybeT = Option<T>;
// ...
}
RunOr this:
fn foo<T>(x: T) {
struct Foo {
x: T,
}
// ...
}
RunItems inside functions are basically just like top-level items, except that they can only be used from the function they are in.
There are a couple of solutions for this.
If the item is a function, you may use a closure:
fn foo<T>(x: T) {
let bar = |y: T| { // explicit type annotation may not be necessary
// ..
};
bar(x);
}
RunFor a generic item, you can copy over the parameters:
fn foo<T>(x: T) {
fn bar<T>(y: T) {
// ..
}
bar(x);
}
Runfn foo<T>(x: T) {
type MaybeT<T> = Option<T>;
}
RunBe sure to copy over any bounds as well:
fn foo<T: Copy>(x: T) {
fn bar<T: Copy>(y: T) {
// ..
}
bar(x);
}
Runfn foo<T: Copy>(x: T) {
struct Foo<T: Copy> {
x: T,
}
}
RunThis may require additional type hints in the function body.
In case the item is a function inside an impl
, defining a private helper
function might be easier:
impl<T> Foo<T> {
pub fn foo(&self, x: T) {
self.bar(x);
}
fn bar(&self, y: T) {
// ..
}
}
RunFor default impls in traits, the private helper solution won’t work, however closures or copying the parameters should still work.
Some type parameters have the same name.
Erroneous code example:
fn f<T, T>(s: T, u: T) {} // error: the name `T` is already used for a generic
// parameter in this item's generic parameters
RunPlease verify that none of the type parameters are misspelled, and rename any clashing parameters. Example:
fn f<T, Y>(s: T, u: Y) {} // ok!
RunType parameters in an associated item also cannot shadow parameters from the containing item:
trait Foo<T> {
fn do_something(&self) -> T;
fn do_something_else<T: Clone>(&self, bar: T);
}
RunA type that is not a trait was used in a trait position, such as a bound
or impl
.
Erroneous code example:
struct Foo;
struct Bar;
impl Foo for Bar {} // error: `Foo` is not a trait
fn baz<T: Foo>(t: T) {} // error: `Foo` is not a trait
RunAnother erroneous code example:
type Foo = Iterator<Item=String>;
fn bar<T: Foo>(t: T) {} // error: `Foo` is a type alias
RunPlease verify that the trait’s name was not misspelled or that the right identifier was used. Example:
trait Foo {
// some functions
}
struct Bar;
impl Foo for Bar { // ok!
// functions implementation
}
fn baz<T: Foo>(t: T) {} // ok!
RunAlternatively, you could introduce a new trait with your desired restrictions as a super trait:
trait Qux: Foo {} // Anything that implements Qux also needs to implement Foo
fn baz<T: Qux>(t: T) {} // also ok!
RunFinally, if you are on nightly and want to use a trait alias
instead of a type alias, you should use #![feature(trait_alias)]
:
#![feature(trait_alias)]
trait Foo = Iterator<Item=String>;
fn bar<T: Foo>(t: T) {} // ok!
RunThe code refers to a trait that is not in scope.
Erroneous code example:
struct Foo;
impl SomeTrait for Foo {} // error: trait `SomeTrait` is not in scope
RunPlease verify that the name of the trait wasn’t misspelled and ensure that it was imported. Example:
// solution 1:
use some_file::SomeTrait;
// solution 2:
trait SomeTrait {
// some functions
}
struct Foo;
impl SomeTrait for Foo { // ok!
// implements functions
}
RunA definition of a method not in the implemented trait was given in a trait implementation.
Erroneous code example:
trait Foo {
fn a();
}
struct Bar;
impl Foo for Bar {
fn a() {}
fn b() {} // error: method `b` is not a member of trait `Foo`
}
RunPlease verify you didn’t misspell the method name and you used the correct trait. First example:
trait Foo {
fn a();
fn b();
}
struct Bar;
impl Foo for Bar {
fn a() {}
fn b() {} // ok!
}
RunSecond example:
trait Foo {
fn a();
}
struct Bar;
impl Foo for Bar {
fn a() {}
}
impl Bar {
fn b() {}
}
RunAn “or” pattern was used where the variable bindings are not consistently bound across patterns.
Erroneous code example:
match x {
Some(y) | None => { /* use y */ } // error: variable `y` from pattern #1 is
// not bound in pattern #2
_ => ()
}
RunHere, y
is bound to the contents of the Some
and can be used within the
block corresponding to the match arm. However, in case x
is None
, we have
not specified what y
is, and the block will use a nonexistent variable.
To fix this error, either split into multiple match arms:
let x = Some(1);
match x {
Some(y) => { /* use y */ }
None => { /* ... */ }
}
Runor, bind the variable to a field of the same type in all sub-patterns of the or pattern:
let x = (0, 2);
match x {
(0, y) | (y, 0) => { /* use y */}
_ => {}
}
RunIn this example, if x
matches the pattern (0, _)
, the second field is set
to y
. If it matches (_, 0)
, the first field is set to y
; so in all
cases y
is set to some value.
An “or” pattern was used where the variable bindings are not consistently bound across patterns.
Erroneous code example:
let x = (0, 2);
match x {
(0, ref y) | (y, 0) => { /* use y */} // error: variable `y` is bound with
// different mode in pattern #2
// than in pattern #1
_ => ()
}
RunHere, y
is bound by-value in one case and by-reference in the other.
To fix this error, just use the same mode in both cases.
Generally using ref
or ref mut
where not already used will fix this:
let x = (0, 2);
match x {
(0, ref y) | (ref y, 0) => { /* use y */}
_ => ()
}
RunAlternatively, split the pattern:
let x = (0, 2);
match x {
(y, 0) => { /* use y */ }
(0, ref y) => { /* use y */}
_ => ()
}
RunThe Self
keyword was used outside an impl, trait, or type definition.
Erroneous code example:
<Self>::foo; // error: use of `Self` outside of an impl, trait, or type
// definition
RunThe Self
keyword represents the current type, which explains why it can only
be used inside an impl, trait, or type definition. It gives access to the
associated items of a type:
trait Foo {
type Bar;
}
trait Baz : Foo {
fn bar() -> Self::Bar; // like this
}
RunHowever, be careful when two types have a common associated type:
trait Foo {
type Bar;
}
trait Foo2 {
type Bar;
}
trait Baz : Foo + Foo2 {
fn bar() -> Self::Bar;
// error: ambiguous associated type `Bar` in bounds of `Self`
}
RunThis problem can be solved by specifying from which trait we want to use the
Bar
type:
trait Foo {
type Bar;
}
trait Foo2 {
type Bar;
}
trait Baz : Foo + Foo2 {
fn bar() -> <Self as Foo>::Bar; // ok!
}
RunA used type name is not in scope.
Erroneous code examples:
impl Something {} // error: type name `Something` is not in scope
// or:
trait Foo {
fn bar(N); // error: type name `N` is not in scope
}
// or:
fn foo(x: T) {} // type name `T` is not in scope
RunTo fix this error, please verify you didn’t misspell the type name, you did declare it or imported it into the scope. Examples:
struct Something;
impl Something {} // ok!
// or:
trait Foo {
type N;
fn bar(_: Self::N); // ok!
}
// or:
fn foo<T>(x: T) {} // ok!
RunAnother case that causes this error is when a type is imported into a parent
module. To fix this, you can follow the suggestion and use File directly or
use super::File;
which will import the types from the parent namespace. An
example that causes this error is below:
use std::fs::File;
mod foo {
fn some_function(f: File) {}
}
Runuse std::fs::File;
mod foo {
// either
use super::File;
// or
// use std::fs::File;
fn foo(f: File) {}
}
RunMore than one function parameter have the same name.
Erroneous code example:
fn foo(f: i32, f: i32) {} // error: identifier `f` is bound more than
// once in this parameter list
RunPlease verify you didn’t misspell parameters’ name. Example:
fn foo(f: i32, g: i32) {} // ok!
RunAn identifier is bound more than once in a pattern.
Erroneous code example:
match (1, 2) {
(x, x) => {} // error: identifier `x` is bound more than once in the
// same pattern
}
RunPlease verify you didn’t misspell identifiers’ name. Example:
match (1, 2) {
(x, y) => {} // ok!
}
RunOr maybe did you mean to unify? Consider using a guard:
match (A, B, C) {
(x, x2, see) if x == x2 => { /* A and B are equal, do one thing */ }
(y, z, see) => { /* A and B unequal; do another thing */ }
}
RunAn identifier that is neither defined nor a struct was used.
Erroneous code example:
fn main () {
let x = Foo { x: 1, y: 2 };
}
RunIn this case, Foo
is undefined, so it inherently isn’t anything, and
definitely not a struct.
fn main () {
let foo = 1;
let x = foo { x: 1, y: 2 };
}
RunIn this case, foo
is defined, but is not a struct, so Rust can’t use it as
one.
An identifier was used like a function name or a value was expected and the identifier exists but it belongs to a different namespace.
Erroneous code example:
struct Foo { a: bool };
let f = Foo();
// error: expected function, tuple struct or tuple variant, found `Foo`
// `Foo` is a struct name, but this expression uses it like a function name
RunPlease verify you didn’t misspell the name of what you actually wanted to use here. Example:
fn Foo() -> u32 { 0 }
let f = Foo(); // ok!
RunIt is common to forget the trailing !
on macro invocations, which would also
yield this error:
println("");
// error: expected function, tuple struct or tuple variant,
// found macro `println`
// did you mean `println!(...)`? (notice the trailing `!`)
RunAnother case where this error is emitted is when a value is expected, but something else is found:
pub mod a {
pub const I: i32 = 1;
}
fn h1() -> i32 {
a.I
//~^ ERROR expected value, found module `a`
// did you mean `a::I`?
}
RunThe self
keyword was used inside of an associated function without a “self
receiver” parameter.
Erroneous code example:
struct Foo;
impl Foo {
// `bar` is a method, because it has a receiver parameter.
fn bar(&self) {}
// `foo` is not a method, because it has no receiver parameter.
fn foo() {
self.bar(); // error: `self` value is a keyword only available in
// methods with a `self` parameter
}
}
RunThe self
keyword can only be used inside methods, which are associated
functions (functions defined inside of a trait
or impl
block) that have a
self
receiver as its first parameter, like self
, &self
, &mut self
or
self: &mut Pin<Self>
(this last one is an example of an “arbitrary self
type”).
Check if the associated function’s parameter list should have contained a self
receiver for it to be a method, and add it if so. Example:
struct Foo;
impl Foo {
fn bar(&self) {}
fn foo(self) { // `foo` is now a method.
self.bar(); // ok!
}
}
RunAn unresolved name was used.
Erroneous code examples:
something_that_doesnt_exist::foo;
// error: unresolved name `something_that_doesnt_exist::foo`
// or:
trait Foo {
fn bar() {
Self; // error: unresolved name `Self`
}
}
// or:
let x = unknown_variable; // error: unresolved name `unknown_variable`
RunPlease verify that the name wasn’t misspelled and ensure that the identifier being referred to is valid for the given situation. Example:
enum something_that_does_exist {
Foo,
}
RunOr:
mod something_that_does_exist {
pub static foo : i32 = 0i32;
}
something_that_does_exist::foo; // ok!
RunOr:
let unknown_variable = 12u32;
let x = unknown_variable; // ok!
RunIf the item is not defined in the current module, it must be imported using a
use
statement, like so:
use foo::bar;
bar();
RunIf the item you are importing is not defined in some super-module of the
current module, then it must also be declared as public (e.g., pub fn
).
An undeclared label was used.
Erroneous code example:
loop {
break 'a; // error: use of undeclared label `'a`
}
RunPlease verify you spelled or declared the label correctly. Example:
'a: loop {
break 'a; // ok!
}
RunA type or module has been defined more than once.
Erroneous code example:
struct Bar;
struct Bar; // error: duplicate definition of value `Bar`
RunPlease verify you didn’t misspell the type/module’s name or remove/rename the duplicated one. Example:
struct Bar;
struct Bar2; // ok!
RunThe self
keyword cannot appear alone as the last segment in a use
declaration.
Erroneous code example:
use std::fmt::self; // error: `self` imports are only allowed within a { } list
RunTo use a namespace itself in addition to some of its members, self
may appear
as part of a brace-enclosed list of imports:
use std::fmt::{self, Debug};
RunIf you only want to import the namespace, do so directly:
use std::fmt;
RunThe self
import appears more than once in the list.
Erroneous code example:
use something::{self, self}; // error: `self` import can only appear once in
// the list
RunPlease verify you didn’t misspell the import name or remove the duplicated
self
import. Example:
use something::{self}; // ok!
RunAn invalid self
import was made.
Erroneous code example:
use {self}; // error: `self` import can only appear in an import list with a
// non-empty prefix
RunYou cannot import the current module into itself, please remove this import or verify you didn’t misspell it.
An import was unresolved.
Erroneous code example:
use something::Foo; // error: unresolved import `something::Foo`.
RunIn Rust 2015, paths in use
statements are relative to the crate root. To
import items relative to the current and parent modules, use the self::
and
super::
prefixes, respectively.
In Rust 2018, paths in use
statements are relative to the current module
unless they begin with the name of a crate or a literal crate::
, in which
case they start from the crate root. As in Rust 2015 code, the self::
and
super::
prefixes refer to the current and parent modules respectively.
Also verify that you didn’t misspell the import name and that the import exists in the module from where you tried to import it. Example:
use self::something::Foo; // Ok.
mod something {
pub struct Foo;
}
RunIf you tried to use a module from an external crate and are using Rust 2015,
you may have missed the extern crate
declaration (which is usually placed in
the crate root):
extern crate core; // Required to use the `core` crate in Rust 2015.
use core::any;
RunIn Rust 2018 the extern crate
declaration is not required and you can instead
just use
it:
use core::any; // No extern crate required in Rust 2018.
RunAn undeclared crate, module, or type was used.
Erroneous code example:
let map = HashMap::new();
// error: failed to resolve: use of undeclared type `HashMap`
RunPlease verify you didn’t misspell the type/module’s name or that you didn’t forget to import it:
use std::collections::HashMap; // HashMap has been imported.
let map: HashMap<u32, u32> = HashMap::new(); // So it can be used!
RunIf you’ve expected to use a crate name:
use ferris_wheel::BigO;
// error: failed to resolve: use of undeclared crate or module `ferris_wheel`
RunMake sure the crate has been added as a dependency in Cargo.toml
.
To use a module from your current crate, add the crate::
prefix to the path.
A variable used inside an inner function comes from a dynamic environment.
Erroneous code example:
fn foo() {
let y = 5;
fn bar() -> u32 {
y // error: can't capture dynamic environment in a fn item; use the
// || { ... } closure form instead.
}
}
RunInner functions do not have access to their containing environment. To fix this error, you can replace the function with a closure:
fn foo() {
let y = 5;
let bar = || {
y
};
}
RunOr replace the captured variable with a constant or a static item:
fn foo() {
static mut X: u32 = 4;
const Y: u32 = 5;
fn bar() -> u32 {
unsafe {
X = 3;
}
Y
}
}
RunA non-constant value was used in a constant expression.
Erroneous code example:
let foo = 42;
let a: [u8; foo]; // error: attempt to use a non-constant value in a constant
Run‘constant’ means ‘a compile-time value’.
More details can be found in the Variables and Mutability section of the book.
To fix this error, please replace the value with a constant. Example:
let a: [u8; 42]; // ok!
RunOr:
const FOO: usize = 42;
let a: [u8; FOO]; // ok!
RunThe functional record update syntax was used on something other than a struct.
Erroneous code example:
enum PublicationFrequency {
Weekly,
SemiMonthly { days: (u8, u8), annual_special: bool },
}
fn one_up_competitor(competitor_frequency: PublicationFrequency)
-> PublicationFrequency {
match competitor_frequency {
PublicationFrequency::Weekly => PublicationFrequency::SemiMonthly {
days: (1, 15), annual_special: false
},
c @ PublicationFrequency::SemiMonthly{ .. } =>
PublicationFrequency::SemiMonthly {
annual_special: true, ..c // error: functional record update
// syntax requires a struct
}
}
}
RunThe functional record update syntax is only allowed for structs (struct-like enum variants don’t qualify, for example). To fix the previous code, rewrite the expression without functional record update syntax:
enum PublicationFrequency {
Weekly,
SemiMonthly { days: (u8, u8), annual_special: bool },
}
fn one_up_competitor(competitor_frequency: PublicationFrequency)
-> PublicationFrequency {
match competitor_frequency {
PublicationFrequency::Weekly => PublicationFrequency::SemiMonthly {
days: (1, 15), annual_special: false
},
PublicationFrequency::SemiMonthly{ days, .. } =>
PublicationFrequency::SemiMonthly {
days, annual_special: true // ok!
}
}
}
RunAn associated type whose name does not match any of the associated types in the trait was used when implementing the trait.
Erroneous code example:
trait Foo {}
impl Foo for i32 {
type Bar = bool;
}
RunTrait implementations can only implement associated types that are members of the trait in question.
The solution to this problem is to remove the extraneous associated type:
trait Foo {}
impl Foo for i32 {}
RunAn associated constant whose name does not match any of the associated constants in the trait was used when implementing the trait.
Erroneous code example:
trait Foo {}
impl Foo for i32 {
const BAR: bool = true;
}
RunTrait implementations can only implement associated constants that are members of the trait in question.
The solution to this problem is to remove the extraneous associated constant:
trait Foo {}
impl Foo for i32 {}
RunThe length of the platform-intrinsic function simd_shuffle
wasn’t specified.
Erroneous code example:
#![feature(platform_intrinsics)]
extern "platform-intrinsic" {
fn simd_shuffle<A,B>(a: A, b: A, c: [u32; 8]) -> B;
// error: invalid `simd_shuffle`, needs length: `simd_shuffle`
}
RunThe simd_shuffle
function needs the length of the array passed as
last parameter in its name. Example:
#![feature(platform_intrinsics)]
extern "platform-intrinsic" {
fn simd_shuffle8<A,B>(a: A, b: A, c: [u32; 8]) -> B;
}
RunA private trait was used on a public type parameter bound.
Erroneous code examples:
#![deny(private_in_public)]
trait Foo {
fn dummy(&self) { }
}
pub trait Bar : Foo {} // error: private trait in public interface
pub struct Bar2<T: Foo>(pub T); // same error
pub fn foo<T: Foo> (t: T) {} // same error
fn main() {}
RunTo solve this error, please ensure that the trait is also public. The trait
can be made inaccessible if necessary by placing it into a private inner
module, but it still has to be marked with pub
. Example:
pub trait Foo { // we set the Foo trait public
fn dummy(&self) { }
}
pub trait Bar : Foo {} // ok!
pub struct Bar2<T: Foo>(pub T); // ok!
pub fn foo<T: Foo> (t: T) {} // ok!
fn main() {}
RunA private type was used in a public type signature.
Erroneous code example:
#![deny(private_in_public)]
struct Bar(u32);
mod foo {
use crate::Bar;
pub fn bar() -> Bar { // error: private type in public interface
Bar(0)
}
}
fn main() {}
RunThere are two ways to solve this error. The first is to make the public type signature only public to a module that also has access to the private type. This is done by using pub(crate) or pub(in crate::my_mod::etc) Example:
struct Bar(u32);
mod foo {
use crate::Bar;
pub(crate) fn bar() -> Bar { // only public to crate root
Bar(0)
}
}
fn main() {}
RunThe other way to solve this error is to make the private type public. Example:
pub struct Bar(u32); // we set the Bar type public
mod foo {
use crate::Bar;
pub fn bar() -> Bar { // ok!
Bar(0)
}
}
fn main() {}
RunThe pub
keyword was used inside a function.
Erroneous code example:
fn foo() {
pub struct Bar; // error: visibility has no effect inside functions
}
RunSince we cannot access items defined inside a function, the visibility of its
items does not impact outer code. So using the pub
keyword in this context
is invalid.
The pub
keyword was used inside a public enum.
Erroneous code example:
pub enum Foo {
pub Bar, // error: unnecessary `pub` visibility
}
RunSince the enum is already public, adding pub
on one its elements is
unnecessary. Example:
enum Foo {
pub Bar, // not ok!
}
RunThis is the correct syntax:
pub enum Foo {
Bar, // ok!
}
RunA visibility qualifier was used when it was unnecessary.
Erroneous code examples:
struct Bar;
trait Foo {
fn foo();
}
pub impl Bar {} // error: unnecessary visibility qualifier
pub impl Foo for Bar { // error: unnecessary visibility qualifier
pub fn foo() {} // error: unnecessary visibility qualifier
}
RunTo fix this error, please remove the visibility qualifier when it is not required. Example:
struct Bar;
trait Foo {
fn foo();
}
// Directly implemented methods share the visibility of the type itself,
// so `pub` is unnecessary here
impl Bar {}
// Trait methods share the visibility of the trait, so `pub` is
// unnecessary in either case
impl Foo for Bar {
fn foo() {}
}
RunA struct constructor with private fields was invoked.
Erroneous code example:
mod Bar {
pub struct Foo {
pub a: isize,
b: isize,
}
}
let f = Bar::Foo{ a: 0, b: 0 }; // error: field `b` of struct `Bar::Foo`
// is private
RunTo fix this error, please ensure that all the fields of the struct are public, or implement a function for easy instantiation. Examples:
mod Bar {
pub struct Foo {
pub a: isize,
pub b: isize, // we set `b` field public
}
}
let f = Bar::Foo{ a: 0, b: 0 }; // ok!
RunOr:
mod Bar {
pub struct Foo {
pub a: isize,
b: isize, // still private
}
impl Foo {
pub fn new() -> Foo { // we create a method to instantiate `Foo`
Foo { a: 0, b: 0 }
}
}
}
let f = Bar::Foo::new(); // ok!
RunAn invalid lint attribute has been given.
Erroneous code example:
#![allow(foo = "")] // error: malformed lint attribute
RunLint attributes only accept a list of identifiers (where each identifier is a lint name). Ensure the attribute is of this form:
#![allow(foo)] // ok!
// or:
#![allow(foo, foo2)] // ok!
RunA lint check attribute was overruled by a forbid
directive set as an
attribute on an enclosing scope, or on the command line with the -F
option.
Example of erroneous code:
#![forbid(non_snake_case)]
#[allow(non_snake_case)]
fn main() {
let MyNumber = 2; // error: allow(non_snake_case) overruled by outer
// forbid(non_snake_case)
}
RunThe forbid
lint setting, like deny
, turns the corresponding compiler
warning into a hard error. Unlike deny
, forbid
prevents itself from being
overridden by inner attributes.
If you’re sure you want to override the lint check, you can change forbid
to
deny
(or use -D
instead of -F
if the forbid
setting was given as a
command-line option) to allow the inner lint check attribute:
#![deny(non_snake_case)]
#[allow(non_snake_case)]
fn main() {
let MyNumber = 2; // ok!
}
RunOtherwise, edit the code to pass the lint check, and remove the overruled attribute:
#![forbid(non_snake_case)]
fn main() {
let my_number = 2;
}
RunA link name was given with an empty name.
Erroneous code example:
#[link(name = "")] extern "C" {}
// error: `#[link(name = "")]` given with empty name
RunThe rust compiler cannot link to an external library if you don’t give it its name. Example:
#[link(name = "some_lib")] extern "C" {} // ok!
RunLinking with kind=framework
is only supported when targeting macOS,
as frameworks are specific to that operating system.
Erroneous code example:
#[link(name = "FooCoreServices", kind = "framework")] extern "C" {}
// OS used to compile is Linux for example
RunTo solve this error you can use conditional compilation:
#[cfg_attr(target="macos", link(name = "FooCoreServices", kind = "framework"))]
extern "C" {}
RunLearn more in the Conditional Compilation section of the Reference.
No description.
An unknown “kind” was specified for a link attribute.
Erroneous code example:
#[link(kind = "wonderful_unicorn")] extern "C" {}
// error: unknown kind: `wonderful_unicorn`
RunPlease specify a valid “kind” value, from one of the following:
A link was used without a name parameter.
Erroneous code example:
#[link(kind = "dylib")] extern "C" {}
// error: `#[link(...)]` specified without `name = "foo"`
RunPlease add the name parameter to allow the rust compiler to find the library you want. Example:
#[link(kind = "dylib", name = "some_lib")] extern "C" {} // ok!
RunNo description.
No description.
No description.
A plugin/crate was declared but cannot be found.
Erroneous code example:
#![feature(plugin)]
#![plugin(cookie_monster)] // error: can't find crate for `cookie_monster`
extern crate cake_is_a_lie; // error: can't find crate for `cake_is_a_lie`
RunYou need to link your code to the relevant crate in order to be able to use it
(through Cargo or the -L
option of rustc example). Plugins are crates as
well, and you link to them the same way.
[dependencies]
in Cargo.toml.package =
under [dependencies]
in Cargo.toml.std
or core
std
prepackaged.
Consider one of the following:
rustup target add
cargo build -Z build-std
#![no_std]
at the crate root, so you won’t need std
in the first
place.x.py build library/std
. More information
about x.py is available in the rustc-dev-guide.The compiler found multiple library files with the requested crate name.
This error can occur in several different cases – for example, when using
extern crate
or passing --extern
options without crate paths. It can also be
caused by caching issues with the build directory, in which case cargo clean
may help.
No description.
Macro import declaration was malformed.
Erroneous code examples:
#[macro_use(a_macro(another_macro))] // error: invalid import declaration
extern crate core as some_crate;
#[macro_use(i_want = "some_macros")] // error: invalid import declaration
extern crate core as another_crate;
RunThis is a syntax error at the level of attribute declarations. The proper syntax for macro imports is the following:
// In some_crate:
#[macro_export]
macro_rules! get_tacos {
...
}
#[macro_export]
macro_rules! get_pimientos {
...
}
// In your crate:
#[macro_use(get_tacos, get_pimientos)] // It imports `get_tacos` and
extern crate some_crate; // `get_pimientos` macros from some_crate
RunIf you would like to import all exported macros, write macro_use
with no
arguments.
A non-root module tried to import macros from another crate.
Example of erroneous code:
mod foo {
#[macro_use(debug_assert)] // error: must be at crate root to import
extern crate core; // macros from another crate
fn run_macro() { debug_assert!(true); }
}
RunOnly extern crate
imports at the crate root level are allowed to import
macros.
Either move the macro import to crate root or do without the foreign macros. This will work:
#[macro_use(debug_assert)] // ok!
extern crate core;
mod foo {
fn run_macro() { debug_assert!(true); }
}
RunA macro listed for import was not found.
Erroneous code example:
#[macro_use(drink, be_merry)] // error: imported macro not found
extern crate alloc;
fn main() {
// ...
}
RunEither the listed macro is not contained in the imported crate, or it is not exported from the given crate.
This could be caused by a typo. Did you misspell the macro’s name?
Double-check the names of the macros listed for import, and that the crate in question exports them.
A working version would be:
// In some_crate crate:
#[macro_export]
macro_rules! eat {
...
}
#[macro_export]
macro_rules! drink {
...
}
// In your crate:
#[macro_use(eat, drink)]
extern crate some_crate; //ok!
RunNo description.
No description.
The type does not fulfill the required lifetime.
Erroneous code example:
use std::sync::Mutex;
struct MyString<'a> {
data: &'a str,
}
fn i_want_static_closure<F>(a: F)
where F: Fn() + 'static {}
fn print_string<'a>(s: Mutex<MyString<'a>>) {
i_want_static_closure(move || { // error: this closure has lifetime 'a
// rather than 'static
println!("{}", s.lock().unwrap().data);
});
}
RunIn this example, the closure does not satisfy the 'static
lifetime constraint.
To fix this error, you need to double check the lifetime of the type. Here, we
can fix this problem by giving s
a static lifetime:
use std::sync::Mutex;
struct MyString<'a> {
data: &'a str,
}
fn i_want_static_closure<F>(a: F)
where F: Fn() + 'static {}
fn print_string(s: Mutex<MyString<'static>>) {
i_want_static_closure(move || { // ok!
println!("{}", s.lock().unwrap().data);
});
}
RunA lifetime bound was not satisfied.
Erroneous code example:
// Check that the explicit lifetime bound (`'SnowWhite`, in this example) must
// outlive all the superbounds from the trait (`'kiss`, in this example).
trait Wedding<'t>: 't { }
struct Prince<'kiss, 'SnowWhite> {
child: Box<Wedding<'kiss> + 'SnowWhite>,
// error: lifetime bound not satisfied
}
RunIn this example, the 'SnowWhite
lifetime is supposed to outlive the 'kiss
lifetime but the declaration of the Prince
struct doesn’t enforce it. To fix
this issue, you need to specify it:
trait Wedding<'t>: 't { }
struct Prince<'kiss, 'SnowWhite: 'kiss> { // You say here that 'SnowWhite
// must live longer than 'kiss.
child: Box<Wedding<'kiss> + 'SnowWhite>, // And now it's all good!
}
RunA lifetime of a returned value does not outlive the function call.
Erroneous code example:
fn prefix<'a>(
words: impl Iterator<Item = &'a str>
) -> impl Iterator<Item = String> { // error!
words.map(|v| format!("foo-{}", v))
}
RunTo fix this error, make the lifetime of the returned value explicit:
fn prefix<'a>(
words: impl Iterator<Item = &'a str> + 'a
) -> impl Iterator<Item = String> + 'a { // ok!
words.map(|v| format!("foo-{}", v))
}
RunThe impl Trait
feature in this example uses an implicit 'static
lifetime
restriction in the returned type. However the type implementing the Iterator
passed to the function lives just as long as 'a
, which is not long enough.
The solution involves adding lifetime bound to both function argument and the return value to make sure that the values inside the iterator are not dropped when the function goes out of the scope.
An alternative solution would be to guarantee that the Item
references
in the iterator are alive for the whole lifetime of the program.
fn prefix(
words: impl Iterator<Item = &'static str>
) -> impl Iterator<Item = String> { // ok!
words.map(|v| format!("foo-{}", v))
}
RunA similar lifetime problem might arise when returning closures:
fn foo(
x: &mut Vec<i32>
) -> impl FnMut(&mut Vec<i32>) -> &[i32] { // error!
|y| {
y.append(x);
y
}
}
RunAnalogically, a solution here is to use explicit return lifetime and move the ownership of the variable to the closure.
fn foo<'a>(
x: &'a mut Vec<i32>
) -> impl FnMut(&mut Vec<i32>) -> &[i32] + 'a { // ok!
move |y| {
y.append(x);
y
}
}
RunTo better understand the lifetime treatment in the impl Trait
,
please see the RFC 1951.
No description.
A reference has a longer lifetime than the data it references.
Erroneous code example:
struct Foo<'a> {
x: fn(&'a i32),
}
trait Trait<'a, 'b> {
type Out;
}
impl<'a, 'b> Trait<'a, 'b> for usize {
type Out = &'a Foo<'b>; // error!
}
RunHere, the problem is that the compiler cannot be sure that the 'b
lifetime
will live longer than 'a
, which should be mandatory in order to be sure that
Trait::Out
will always have a reference pointing to an existing type. So in
this case, we just need to tell the compiler than 'b
must outlive 'a
:
struct Foo<'a> {
x: fn(&'a i32),
}
trait Trait<'a, 'b> {
type Out;
}
impl<'a, 'b: 'a> Trait<'a, 'b> for usize { // we added the lifetime enforcement
type Out = &'a Foo<'b>; // it now works!
}
RunA borrow of a constant containing interior mutability was attempted.
Erroneous code example:
use std::sync::atomic::AtomicUsize;
const A: AtomicUsize = AtomicUsize::new(0);
const B: &'static AtomicUsize = &A;
// error: cannot borrow a constant which may contain interior mutability,
// create a static instead
RunA const
represents a constant value that should never change. If one takes
a &
reference to the constant, then one is taking a pointer to some memory
location containing the value. Normally this is perfectly fine: most values
can’t be changed via a shared &
pointer, but interior mutability would allow
it. That is, a constant value could be mutated. On the other hand, a static
is
explicitly a single memory location, which can be mutated at will.
So, in order to solve this error, use statics which are Sync
:
use std::sync::atomic::AtomicUsize;
static A: AtomicUsize = AtomicUsize::new(0);
static B: &'static AtomicUsize = &A; // ok!
RunYou can also have this error while using a cell type:
use std::cell::Cell;
const A: Cell<usize> = Cell::new(1);
const B: &Cell<usize> = &A;
// error: cannot borrow a constant which may contain interior mutability,
// create a static instead
// or:
struct C { a: Cell<usize> }
const D: C = C { a: Cell::new(1) };
const E: &Cell<usize> = &D.a; // error
// or:
const F: &C = &D; // error
RunThis is because cell types do operations that are not thread-safe. Due to this, they don’t implement Sync and thus can’t be placed in statics.
However, if you still wish to use these types, you can achieve this by an unsafe wrapper:
use std::cell::Cell;
use std::marker::Sync;
struct NotThreadSafe<T> {
value: Cell<T>,
}
unsafe impl<T> Sync for NotThreadSafe<T> {}
static A: NotThreadSafe<usize> = NotThreadSafe { value : Cell::new(1) };
static B: &'static NotThreadSafe<usize> = &A; // ok!
RunRemember this solution is unsafe! You will have to ensure that accesses to the cell are synchronized.
A value with a custom Drop
implementation may be dropped during const-eval.
Erroneous code example:
enum DropType {
A,
}
impl Drop for DropType {
fn drop(&mut self) {}
}
struct Foo {
field1: DropType,
}
static FOO: Foo = Foo { field1: (DropType::A, DropType::A).1 }; // error!
RunThe problem here is that if the given type or one of its fields implements the
Drop
trait, this Drop
implementation cannot be called within a const
context since it may run arbitrary, non-const-checked code. To prevent this
issue, ensure all values with a custom Drop
implementation escape the
initializer.
enum DropType {
A,
}
impl Drop for DropType {
fn drop(&mut self) {}
}
struct Foo {
field1: DropType,
}
static FOO: Foo = Foo { field1: DropType::A }; // We initialize all fields
// by hand.
RunA lifetime cannot be determined in the given situation.
Erroneous code example:
fn transmute_lifetime<'a, 'b, T>(t: &'a (T,)) -> &'b T {
match (&t,) { // error!
((u,),) => u,
}
}
let y = Box::new((42,));
let x = transmute_lifetime(&y);
RunIn this code, you have two ways to solve this issue:
'a
lives at least as long as 'b
.So for the first solution, you can do it by replacing 'a
with 'a: 'b
:
fn transmute_lifetime<'a: 'b, 'b, T>(t: &'a (T,)) -> &'b T {
match (&t,) { // ok!
((u,),) => u,
}
}
RunIn the second you can do it by simply removing 'b
so they both use 'a
:
fn transmute_lifetime<'a, T>(t: &'a (T,)) -> &'a T {
match (&t,) { // ok!
((u,),) => u,
}
}
RunA lifetime name is shadowing another lifetime name.
Erroneous code example:
struct Foo<'a> {
a: &'a i32,
}
impl<'a> Foo<'a> {
fn f<'a>(x: &'a i32) { // error: lifetime name `'a` shadows a lifetime
// name that is already in scope
}
}
RunPlease change the name of one of the lifetimes to remove this error. Example:
struct Foo<'a> {
a: &'a i32,
}
impl<'a> Foo<'a> {
fn f<'b>(x: &'b i32) { // ok!
}
}
fn main() {
}
RunA stability attribute was used outside of the standard library.
Erroneous code example:
#[stable] // error: stability attributes may not be used outside of the
// standard library
fn foo() {}
RunIt is not possible to use stability attributes outside of the standard library. Also, for now, it is not possible to write deprecation messages either.
The plugin
attribute was malformed.
Erroneous code example:
#![feature(plugin)]
#![plugin(foo(args))] // error: invalid argument
#![plugin(bar="test")] // error: invalid argument
RunThe #[plugin]
attribute should take a single argument: the name of the plugin.
For example, for the plugin foo
:
#![feature(plugin)]
#![plugin(foo)] // ok!
RunSee the plugin
feature section of the Unstable book for more details.
A variable was borrowed as mutable more than once.
Erroneous code example:
let mut i = 0;
let mut x = &mut i;
let mut a = &mut i;
x;
// error: cannot borrow `i` as mutable more than once at a time
RunPlease note that in Rust, you can either have many immutable references, or one mutable reference. For more details you may want to read the References & Borrowing section of the Book.
Example:
let mut i = 0;
let mut x = &mut i; // ok!
// or:
let mut i = 0;
let a = &i; // ok!
let b = &i; // still ok!
let c = &i; // still ok!
b;
a;
RunA borrowed variable was used by a closure.
Erroneous code example:
fn you_know_nothing(jon_snow: &mut i32) {
let nights_watch = &jon_snow;
let starks = || {
*jon_snow = 3; // error: closure requires unique access to `jon_snow`
// but it is already borrowed
};
println!("{}", nights_watch);
}
RunIn here, jon_snow
is already borrowed by the nights_watch
reference, so it
cannot be borrowed by the starks
closure at the same time. To fix this issue,
you can create the closure after the borrow has ended:
fn you_know_nothing(jon_snow: &mut i32) {
let nights_watch = &jon_snow;
println!("{}", nights_watch);
let starks = || {
*jon_snow = 3;
};
}
RunOr, if the type implements the Clone
trait, you can clone it between
closures:
fn you_know_nothing(jon_snow: &mut i32) {
let mut jon_copy = jon_snow.clone();
let starks = || {
*jon_snow = 3;
};
println!("{}", jon_copy);
}
RunA mutable variable is used but it is already captured by a closure.
Erroneous code example:
fn inside_closure(x: &mut i32) {
// Actions which require unique access
}
fn outside_closure(x: &mut i32) {
// Actions which require unique access
}
fn foo(a: &mut i32) {
let mut bar = || {
inside_closure(a)
};
outside_closure(a); // error: cannot borrow `*a` as mutable because previous
// closure requires unique access.
bar();
}
RunThis error indicates that a mutable variable is used while it is still captured by a closure. Because the closure has borrowed the variable, it is not available until the closure goes out of scope.
Note that a capture will either move or borrow a variable, but in this situation, the closure is borrowing the variable. Take a look at the chapter on Capturing in Rust By Example for more information.
To fix this error, you can finish using the closure before using the captured variable:
fn inside_closure(x: &mut i32) {}
fn outside_closure(x: &mut i32) {}
fn foo(a: &mut i32) {
let mut bar = || {
inside_closure(a)
};
bar();
// borrow on `a` ends.
outside_closure(a); // ok!
}
RunOr you can pass the variable as a parameter to the closure:
fn inside_closure(x: &mut i32) {}
fn outside_closure(x: &mut i32) {}
fn foo(a: &mut i32) {
let mut bar = |s: &mut i32| {
inside_closure(s)
};
outside_closure(a);
bar(a);
}
RunIt may be possible to define the closure later:
fn inside_closure(x: &mut i32) {}
fn outside_closure(x: &mut i32) {}
fn foo(a: &mut i32) {
outside_closure(a);
let mut bar = || {
inside_closure(a)
};
bar();
}
RunA variable already borrowed as immutable was borrowed as mutable.
Erroneous code example:
fn bar(x: &mut i32) {}
fn foo(a: &mut i32) {
let y = &a; // a is borrowed as immutable.
bar(a); // error: cannot borrow `*a` as mutable because `a` is also borrowed
// as immutable
println!("{}", y);
}
RunTo fix this error, ensure that you don’t have any other references to the variable before trying to access it mutably:
fn bar(x: &mut i32) {}
fn foo(a: &mut i32) {
bar(a);
let y = &a; // ok!
println!("{}", y);
}
RunFor more information on Rust’s ownership system, take a look at the References & Borrowing section of the Book.
A value was used after it was mutably borrowed.
Erroneous code example:
fn main() {
let mut value = 3;
// Create a mutable borrow of `value`.
let borrow = &mut value;
let _sum = value + 1; // error: cannot use `value` because
// it was mutably borrowed
println!("{}", borrow);
}
RunIn this example, value
is mutably borrowed by borrow
and cannot be
used to calculate sum
. This is not possible because this would violate
Rust’s mutability rules.
You can fix this error by finishing using the borrow before the next use of the value:
fn main() {
let mut value = 3;
let borrow = &mut value;
println!("{}", borrow);
// The block has ended and with it the borrow.
// You can now use `value` again.
let _sum = value + 1;
}
RunOr by cloning value
before borrowing it:
fn main() {
let mut value = 3;
// We clone `value`, creating a copy.
let value_cloned = value.clone();
// The mutable borrow is a reference to `value` and
// not to `value_cloned`...
let borrow = &mut value;
// ... which means we can still use `value_cloned`,
let _sum = value_cloned + 1;
// even though the borrow only ends here.
println!("{}", borrow);
}
RunFor more information on Rust’s ownership system, take a look at the References & Borrowing section of the Book.
This error occurs when an attempt is made to move a borrowed variable into a closure.
Erroneous code example:
struct FancyNum {
num: u8,
}
fn main() {
let fancy_num = FancyNum { num: 5 };
let fancy_ref = &fancy_num;
let x = move || {
println!("child function: {}", fancy_num.num);
// error: cannot move `fancy_num` into closure because it is borrowed
};
x();
println!("main function: {}", fancy_ref.num);
}
RunHere, fancy_num
is borrowed by fancy_ref
and so cannot be moved into
the closure x
. There is no way to move a value into a closure while it is
borrowed, as that would invalidate the borrow.
If the closure can’t outlive the value being moved, try using a reference rather than moving:
struct FancyNum {
num: u8,
}
fn main() {
let fancy_num = FancyNum { num: 5 };
let fancy_ref = &fancy_num;
let x = move || {
// fancy_ref is usable here because it doesn't move `fancy_num`
println!("child function: {}", fancy_ref.num);
};
x();
println!("main function: {}", fancy_num.num);
}
RunIf the value has to be borrowed and then moved, try limiting the lifetime of the borrow using a scoped block:
struct FancyNum {
num: u8,
}
fn main() {
let fancy_num = FancyNum { num: 5 };
{
let fancy_ref = &fancy_num;
println!("main function: {}", fancy_ref.num);
// `fancy_ref` goes out of scope here
}
let x = move || {
// `fancy_num` can be moved now (no more references exist)
println!("child function: {}", fancy_num.num);
};
x();
}
RunIf the lifetime of a reference isn’t enough, such as in the case of threading,
consider using an Arc
to create a reference-counted value:
use std::sync::Arc;
use std::thread;
struct FancyNum {
num: u8,
}
fn main() {
let fancy_ref1 = Arc::new(FancyNum { num: 5 });
let fancy_ref2 = fancy_ref1.clone();
let x = thread::spawn(move || {
// `fancy_ref1` can be moved and has a `'static` lifetime
println!("child thread: {}", fancy_ref1.num);
});
x.join().expect("child thread should finish");
println!("main thread: {}", fancy_ref2.num);
}
RunA value was moved out while it was still borrowed.
Erroneous code example:
struct Value {}
fn borrow(val: &Value) {}
fn eat(val: Value) {}
fn main() {
let x = Value{};
let _ref_to_val: &Value = &x;
eat(x);
borrow(_ref_to_val);
}
RunHere, the function eat
takes ownership of x
. However,
x
cannot be moved because the borrow to _ref_to_val
needs to last till the function borrow
.
To fix that you can do a few different things:
Copy
trait on the type.Examples:
struct Value {}
fn borrow(val: &Value) {}
fn eat(val: &Value) {}
fn main() {
let x = Value{};
let ref_to_val: &Value = &x;
eat(&x); // pass by reference, if it's possible
borrow(ref_to_val);
}
RunOr:
struct Value {}
fn borrow(val: &Value) {}
fn eat(val: Value) {}
fn main() {
let x = Value{};
let ref_to_val: &Value = &x;
borrow(ref_to_val);
// ref_to_val is no longer used.
eat(x);
}
RunOr:
#[derive(Clone, Copy)] // implement Copy trait
struct Value {}
fn borrow(val: &Value) {}
fn eat(val: Value) {}
fn main() {
let x = Value{};
let ref_to_val: &Value = &x;
eat(x); // it will be copied here.
borrow(ref_to_val);
}
RunFor more information on Rust’s ownership system, take a look at the References & Borrowing section of the Book.
An attempt was made to assign to a borrowed value.
Erroneous code example:
struct FancyNum {
num: u8,
}
let mut fancy_num = FancyNum { num: 5 };
let fancy_ref = &fancy_num;
fancy_num = FancyNum { num: 6 };
// error: cannot assign to `fancy_num` because it is borrowed
println!("Num: {}, Ref: {}", fancy_num.num, fancy_ref.num);
RunBecause fancy_ref
still holds a reference to fancy_num
, fancy_num
can’t
be assigned to a new value as it would invalidate the reference.
Alternatively, we can move out of fancy_num
into a second fancy_num
:
struct FancyNum {
num: u8,
}
let mut fancy_num = FancyNum { num: 5 };
let moved_num = fancy_num;
fancy_num = FancyNum { num: 6 };
println!("Num: {}, Moved num: {}", fancy_num.num, moved_num.num);
RunIf the value has to be borrowed, try limiting the lifetime of the borrow using a scoped block:
struct FancyNum {
num: u8,
}
let mut fancy_num = FancyNum { num: 5 };
{
let fancy_ref = &fancy_num;
println!("Ref: {}", fancy_ref.num);
}
// Works because `fancy_ref` is no longer in scope
fancy_num = FancyNum { num: 6 };
println!("Num: {}", fancy_num.num);
RunOr by moving the reference into a function:
struct FancyNum {
num: u8,
}
fn print_fancy_ref(fancy_ref: &FancyNum){
println!("Ref: {}", fancy_ref.num);
}
let mut fancy_num = FancyNum { num: 5 };
print_fancy_ref(&fancy_num);
// Works because function borrow has ended
fancy_num = FancyNum { num: 6 };
println!("Num: {}", fancy_num.num);
RunA borrowed value was moved out.
Erroneous code example:
use std::cell::RefCell;
struct TheDarkKnight;
impl TheDarkKnight {
fn nothing_is_true(self) {}
}
fn main() {
let x = RefCell::new(TheDarkKnight);
x.borrow().nothing_is_true(); // error: cannot move out of borrowed content
}
RunHere, the nothing_is_true
method takes the ownership of self
. However,
self
cannot be moved because .borrow()
only provides an &TheDarkKnight
,
which is a borrow of the content owned by the RefCell
. To fix this error,
you have three choices:
Copy
trait on the type.This can also happen when using a type implementing Fn
or FnMut
, as neither
allows moving out of them (they usually represent closures which can be called
more than once). Much of the text following applies equally well to non-FnOnce
closure bodies.
Examples:
use std::cell::RefCell;
struct TheDarkKnight;
impl TheDarkKnight {
fn nothing_is_true(&self) {} // First case, we don't take ownership
}
fn main() {
let x = RefCell::new(TheDarkKnight);
x.borrow().nothing_is_true(); // ok!
}
RunOr:
use std::cell::RefCell;
struct TheDarkKnight;
impl TheDarkKnight {
fn nothing_is_true(self) {}
}
fn main() {
let x = RefCell::new(TheDarkKnight);
let x = x.into_inner(); // we get back ownership
x.nothing_is_true(); // ok!
}
RunOr:
use std::cell::RefCell;
#[derive(Clone, Copy)] // we implement the Copy trait
struct TheDarkKnight;
impl TheDarkKnight {
fn nothing_is_true(self) {}
}
fn main() {
let x = RefCell::new(TheDarkKnight);
x.borrow().nothing_is_true(); // ok!
}
RunMoving a member out of a mutably borrowed struct will also cause E0507 error:
struct TheDarkKnight;
impl TheDarkKnight {
fn nothing_is_true(self) {}
}
struct Batcave {
knight: TheDarkKnight
}
fn main() {
let mut cave = Batcave {
knight: TheDarkKnight
};
let borrowed = &mut cave;
borrowed.knight.nothing_is_true(); // E0507
}
RunIt is fine only if you put something back. mem::replace
can be used for that:
use std::mem;
let mut cave = Batcave {
knight: TheDarkKnight
};
let borrowed = &mut cave;
mem::replace(&mut borrowed.knight, TheDarkKnight).nothing_is_true(); // ok!
RunFor more information on Rust’s ownership system, take a look at the References & Borrowing section of the Book.
A value was moved out of a non-copy fixed-size array.
Erroneous code example:
struct NonCopy;
fn main() {
let array = [NonCopy; 1];
let _value = array[0]; // error: cannot move out of type `[NonCopy; 1]`,
// a non-copy fixed-size array
}
RunThe first element was moved out of the array, but this is not
possible because NonCopy
does not implement the Copy
trait.
Consider borrowing the element instead of moving it:
struct NonCopy;
fn main() {
let array = [NonCopy; 1];
let _value = &array[0]; // Borrowing is allowed, unlike moving.
}
RunAlternatively, if your type implements Clone
and you need to own the value,
consider borrowing and then cloning:
#[derive(Clone)]
struct NonCopy;
fn main() {
let array = [NonCopy; 1];
// Now you can clone the array element.
let _value = array[0].clone();
}
RunIf you really want to move the value out, you can use a destructuring array pattern to move it:
struct NonCopy;
fn main() {
let array = [NonCopy; 1];
// Destructuring the array
let [_value] = array;
}
RunThis error occurs when an attempt is made to move out of a value whose type
implements the Drop
trait.
Erroneous code example:
struct FancyNum {
num: usize
}
struct DropStruct {
fancy: FancyNum
}
impl Drop for DropStruct {
fn drop(&mut self) {
// Destruct DropStruct, possibly using FancyNum
}
}
fn main() {
let drop_struct = DropStruct{fancy: FancyNum{num: 5}};
let fancy_field = drop_struct.fancy; // Error E0509
println!("Fancy: {}", fancy_field.num);
// implicit call to `drop_struct.drop()` as drop_struct goes out of scope
}
RunHere, we tried to move a field out of a struct of type DropStruct
which
implements the Drop
trait. However, a struct cannot be dropped if one or
more of its fields have been moved.
Structs implementing the Drop
trait have an implicit destructor that gets
called when they go out of scope. This destructor may use the fields of the
struct, so moving out of the struct could make it impossible to run the
destructor. Therefore, we must think of all values whose type implements the
Drop
trait as single units whose fields cannot be moved.
This error can be fixed by creating a reference to the fields of a struct,
enum, or tuple using the ref
keyword:
struct FancyNum {
num: usize
}
struct DropStruct {
fancy: FancyNum
}
impl Drop for DropStruct {
fn drop(&mut self) {
// Destruct DropStruct, possibly using FancyNum
}
}
fn main() {
let drop_struct = DropStruct{fancy: FancyNum{num: 5}};
let ref fancy_field = drop_struct.fancy; // No more errors!
println!("Fancy: {}", fancy_field.num);
// implicit call to `drop_struct.drop()` as drop_struct goes out of scope
}
RunNote that this technique can also be used in the arms of a match expression:
struct FancyNum {
num: usize
}
enum DropEnum {
Fancy(FancyNum)
}
impl Drop for DropEnum {
fn drop(&mut self) {
// Destruct DropEnum, possibly using FancyNum
}
}
fn main() {
// Creates and enum of type `DropEnum`, which implements `Drop`
let drop_enum = DropEnum::Fancy(FancyNum{num: 10});
match drop_enum {
// Creates a reference to the inside of `DropEnum::Fancy`
DropEnum::Fancy(ref fancy_field) => // No error!
println!("It was fancy-- {}!", fancy_field.num),
}
// implicit call to `drop_enum.drop()` as drop_enum goes out of scope
}
RunThe matched value was assigned in a match guard.
Erroneous code example:
let mut x = Some(0);
match x {
None => {}
Some(_) if { x = None; false } => {} // error!
Some(_) => {}
}
RunWhen matching on a variable it cannot be mutated in the match guards, as this could cause the match to be non-exhaustive.
Here executing x = None
would modify the value being matched and require us
to go “back in time” to the None
arm. To fix it, change the value in the match
arm:
let mut x = Some(0);
match x {
None => {}
Some(_) => {
x = None; // ok!
}
}
RunInvalid monomorphization of an intrinsic function was used.
Erroneous code example:
#![feature(platform_intrinsics)]
extern "platform-intrinsic" {
fn simd_add<T>(a: T, b: T) -> T;
}
fn main() {
unsafe { simd_add(0, 1); }
// error: invalid monomorphization of `simd_add` intrinsic
}
RunThe generic type has to be a SIMD type. Example:
#![feature(repr_simd)]
#![feature(platform_intrinsics)]
#[repr(simd)]
#[derive(Copy, Clone)]
struct i32x2(i32, i32);
extern "platform-intrinsic" {
fn simd_add<T>(a: T, b: T) -> T;
}
unsafe { simd_add(i32x2(0, 0), i32x2(1, 2)); } // ok!
RunTransmute with two differently sized types was attempted.
Erroneous code example:
fn takes_u8(_: u8) {}
fn main() {
unsafe { takes_u8(::std::mem::transmute(0u16)); }
// error: cannot transmute between types of different sizes,
// or dependently-sized types
}
RunPlease use types with same size or use the expected type directly. Example:
fn takes_u8(_: u8) {}
fn main() {
unsafe { takes_u8(::std::mem::transmute(0i8)); } // ok!
// or:
unsafe { takes_u8(0u8); } // ok!
}
RunNo description.
A reference to a local variable was returned.
Erroneous code example:
fn get_dangling_reference() -> &'static i32 {
let x = 0;
&x
}
Runuse std::slice::Iter;
fn get_dangling_iterator<'a>() -> Iter<'a, i32> {
let v = vec![1, 2, 3];
v.iter()
}
RunLocal variables, function parameters and temporaries are all dropped before the end of the function body. So a reference to them cannot be returned.
Consider returning an owned value instead:
use std::vec::IntoIter;
fn get_integer() -> i32 {
let x = 0;
x
}
fn get_owned_iterator() -> IntoIter<i32> {
let v = vec![1, 2, 3];
v.into_iter()
}
RunThe typeof
keyword is currently reserved but unimplemented.
Erroneous code example:
fn main() {
let x: typeof(92) = 92;
}
RunTry using type inference instead. Example:
fn main() {
let x = 92;
}
RunA #[repr(..)]
attribute was placed on an unsupported item.
Examples of erroneous code:
#[repr(C)]
type Foo = u8;
#[repr(packed)]
enum Foo {Bar, Baz}
#[repr(u8)]
struct Foo {bar: bool, baz: bool}
#[repr(C)]
impl Foo {
// ...
}
Run#[repr(C)]
attribute can only be placed on structs and enums.#[repr(packed)]
and #[repr(simd)]
attributes only work on structs.#[repr(u8)]
, #[repr(i16)]
, etc attributes only work on enums.These attributes do not work on typedefs, since typedefs are just aliases.
Representations like #[repr(u8)]
, #[repr(i64)]
are for selecting the
discriminant size for enums with no data fields on any of the variants, e.g.
enum Color {Red, Blue, Green}
, effectively setting the size of the enum to
the size of the provided type. Such an enum can be cast to a value of the same
type as well. In short, #[repr(u8)]
makes the enum behave like an integer
with a constrained set of allowed values.
Only field-less enums can be cast to numerical primitives, so this attribute will not apply to structs.
#[repr(packed)]
reduces padding to make the struct size smaller. The
representation of enums isn’t strictly defined in Rust, and this attribute
won’t work on enums.
#[repr(simd)]
will give a struct consisting of a homogeneous series of machine
types (i.e., u8
, i32
, etc) a representation that permits vectorization via
SIMD. This doesn’t make much sense for enums since they don’t consist of a
single list of data.
An #[inline(..)]
attribute was incorrectly placed on something other than a
function or method.
Example of erroneous code:
#[inline(always)]
struct Foo;
#[inline(never)]
impl Foo {
// ...
}
Run#[inline]
hints the compiler whether or not to attempt to inline a method or
function. By default, the compiler does a pretty good job of figuring this out
itself, but if you feel the need for annotations, #[inline(always)]
and
#[inline(never)]
can override or force the compiler’s decision.
If you wish to apply this attribute to all methods in an impl, manually annotate
each method; it is not possible to annotate the entire impl with an #[inline]
attribute.
No description.
A non-default implementation was already made on this type so it cannot be specialized further.
Erroneous code example:
#![feature(specialization)]
trait SpaceLlama {
fn fly(&self);
}
// applies to all T
impl<T> SpaceLlama for T {
default fn fly(&self) {}
}
// non-default impl
// applies to all `Clone` T and overrides the previous impl
impl<T: Clone> SpaceLlama for T {
fn fly(&self) {}
}
// since `i32` is clone, this conflicts with the previous implementation
impl SpaceLlama for i32 {
default fn fly(&self) {}
// error: item `fly` is provided by an `impl` that specializes
// another, but the item in the parent `impl` is not marked
// `default` and so it cannot be specialized.
}
RunSpecialization only allows you to override default
functions in
implementations.
To fix this error, you need to mark all the parent implementations as default. Example:
#![feature(specialization)]
trait SpaceLlama {
fn fly(&self);
}
// applies to all T
impl<T> SpaceLlama for T {
default fn fly(&self) {} // This is a parent implementation.
}
// applies to all `Clone` T; overrides the previous impl
impl<T: Clone> SpaceLlama for T {
default fn fly(&self) {} // This is a parent implementation but was
// previously not a default one, causing the error
}
// applies to i32, overrides the previous two impls
impl SpaceLlama for i32 {
fn fly(&self) {} // And now that's ok!
}
RunBorrowed data escapes outside of closure.
Erroneous code example:
let mut list: Vec<&str> = Vec::new();
let _add = |el: &str| {
list.push(el); // error: `el` escapes the closure body here
};
RunA type anotation of a closure parameter implies a new lifetime declaration. Consider to drop it, the compiler is reliably able to infer them.
let mut list: Vec<&str> = Vec::new();
let _add = |el| {
list.push(el);
};
RunSee the Closure type inference and annotation and Lifetime elision sections of the Book for more details.
The lang attribute was used in an invalid context.
Erroneous code example:
#![feature(lang_items)]
#[lang = "cookie"]
fn cookie() -> ! { // error: definition of an unknown language item: `cookie`
loop {}
}
RunThe lang attribute is intended for marking special items that are built-in to
Rust itself. This includes special traits (like Copy
and Sized
) that affect
how the compiler behaves, as well as special functions that may be automatically
invoked (such as the handler for out-of-bounds accesses when indexing a slice).
No description.
A variable which requires unique access is being used in more than one closure at the same time.
Erroneous code example:
fn set(x: &mut isize) {
*x += 4;
}
fn dragoooon(x: &mut isize) {
let mut c1 = || set(x);
let mut c2 = || set(x); // error!
c2();
c1();
}
RunTo solve this issue, multiple solutions are available. First, is it required
for this variable to be used in more than one closure at a time? If it is the
case, use reference counted types such as Rc
(or Arc
if it runs
concurrently):
use std::rc::Rc;
use std::cell::RefCell;
fn set(x: &mut isize) {
*x += 4;
}
fn dragoooon(x: &mut isize) {
let x = Rc::new(RefCell::new(x));
let y = Rc::clone(&x);
let mut c1 = || { let mut x2 = x.borrow_mut(); set(&mut x2); };
let mut c2 = || { let mut x2 = y.borrow_mut(); set(&mut x2); }; // ok!
c2();
c1();
}
RunIf not, just run closures one at a time:
fn set(x: &mut isize) {
*x += 4;
}
fn dragoooon(x: &mut isize) {
{ // This block isn't necessary since non-lexical lifetimes, it's just to
// make it more clear.
let mut c1 = || set(&mut *x);
c1();
} // `c1` has been dropped here so we're free to use `x` again!
let mut c2 = || set(&mut *x);
c2();
}
RunA closure was used but didn’t implement the expected trait.
Erroneous code example:
struct X;
fn foo<T>(_: T) {}
fn bar<T: Fn(u32)>(_: T) {}
fn main() {
let x = X;
let closure = |_| foo(x); // error: expected a closure that implements
// the `Fn` trait, but this closure only
// implements `FnOnce`
bar(closure);
}
RunIn the example above, closure
is an FnOnce
closure whereas the bar
function expected an Fn
closure. In this case, it’s simple to fix the issue,
you just have to implement Copy
and Clone
traits on struct X
and it’ll
be ok:
#[derive(Clone, Copy)] // We implement `Clone` and `Copy` traits.
struct X;
fn foo<T>(_: T) {}
fn bar<T: Fn(u32)>(_: T) {}
fn main() {
let x = X;
let closure = |_| foo(x);
bar(closure); // ok!
}
RunTo better understand how these work in Rust, read the Closures chapter of the Book.
The number of elements in an array or slice pattern differed from the number of elements in the array being matched.
Example of erroneous code:
let r = &[1, 2, 3, 4];
match r {
&[a, b] => { // error: pattern requires 2 elements but array
// has 4
println!("a={}, b={}", a, b);
}
}
RunEnsure that the pattern is consistent with the size of the matched
array. Additional elements can be matched with ..
:
let r = &[1, 2, 3, 4];
match r {
&[a, b, ..] => { // ok!
println!("a={}, b={}", a, b);
}
}
RunAn array or slice pattern required more elements than were present in the matched array.
Example of erroneous code:
let r = &[1, 2];
match r {
&[a, b, c, rest @ ..] => { // error: pattern requires at least 3
// elements but array has 2
println!("a={}, b={}, c={} rest={:?}", a, b, c, rest);
}
}
RunEnsure that the matched array has at least as many elements as the pattern
requires. You can match an arbitrary number of remaining elements with ..
:
let r = &[1, 2, 3, 4, 5];
match r {
&[a, b, c, rest @ ..] => { // ok!
// prints `a=1, b=2, c=3 rest=[4, 5]`
println!("a={}, b={}, c={} rest={:?}", a, b, c, rest);
}
}
RunAn array or slice pattern was matched against some other type.
Example of erroneous code:
let r: f32 = 1.0;
match r {
[a, b] => { // error: expected an array or slice, found `f32`
println!("a={}, b={}", a, b);
}
}
RunEnsure that the pattern and the expression being matched on are of consistent types:
let r = [1.0, 2.0];
match r {
[a, b] => { // ok!
println!("a={}, b={}", a, b);
}
}
RunA binding shadowed something it shouldn’t.
A match arm or a variable has a name that is already used by something else, e.g.
This error may also happen when an enum variant with fields is used in a pattern, but without its fields.
enum Enum {
WithField(i32)
}
use Enum::*;
match WithField(1) {
WithField => {} // error: missing (_)
}
RunMatch bindings cannot shadow statics:
static TEST: i32 = 0;
let r = 123;
match r {
TEST => {} // error: name of a static
}
RunFixed examples:
static TEST: i32 = 0;
let r = 123;
match r {
some_value => {} // ok!
}
Runor
const TEST: i32 = 0; // const, not static
let r = 123;
match r {
TEST => {} // const is ok!
other_values => {}
}
RunAn unknown tuple struct/variant has been used.
Erroneous code example:
let Type(x) = Type(12); // error!
match Bar(12) {
Bar(x) => {} // error!
_ => {}
}
RunIn most cases, it’s either a forgotten import or a typo. However, let’s look at how you can have such a type:
struct Type(u32); // this is a tuple struct
enum Foo {
Bar(u32), // this is a tuple variant
}
use Foo::*; // To use Foo's variant directly, we need to import them in
// the scope.
RunEither way, it should work fine with our previous code:
struct Type(u32);
enum Foo {
Bar(u32),
}
use Foo::*;
let Type(x) = Type(12); // ok!
match Type(12) {
Type(x) => {} // ok!
_ => {}
}
RunPattern arm did not match expected kind.
Erroneous code example:
enum State {
Succeeded,
Failed(String),
}
fn print_on_failure(state: &State) {
match *state {
// error: expected unit struct, unit variant or constant, found tuple
// variant `State::Failed`
State::Failed => println!("Failed"),
_ => ()
}
}
RunTo fix this error, ensure the match arm kind is the same as the expression matched.
Fixed example:
enum State {
Succeeded,
Failed(String),
}
fn print_on_failure(state: &State) {
match *state {
State::Failed(ref msg) => println!("Failed with {}", msg),
_ => ()
}
}
RunAn item which isn’t a unit struct, a variant, nor a constant has been used as a match pattern.
Erroneous code example:
struct Tortoise;
impl Tortoise {
fn turtle(&self) -> u32 { 0 }
}
match 0u32 {
Tortoise::turtle => {} // Error!
_ => {}
}
if let Tortoise::turtle = 0u32 {} // Same error!
RunIf you want to match against a value returned by a method, you need to bind the value first:
struct Tortoise;
impl Tortoise {
fn turtle(&self) -> u32 { 0 }
}
match 0u32 {
x if x == Tortoise.turtle() => {} // Bound into `x` then we compare it!
_ => {}
}
RunThe inline
attribute was malformed.
Erroneous code example:
#[inline()] // error: expected one argument
pub fn something() {}
fn main() {}
RunThe parenthesized inline
attribute requires the parameter to be specified:
#[inline(always)]
fn something() {}
Runor:
#[inline(never)]
fn something() {}
RunAlternatively, a paren-less version of the attribute may be used to hint the compiler about inlining opportunity:
#[inline]
fn something() {}
RunFor more information see the inline
attribute section
of the Reference.
An unknown argument was given to the inline
attribute.
Erroneous code example:
#[inline(unknown)] // error: invalid argument
pub fn something() {}
fn main() {}
RunThe inline
attribute only supports two arguments:
All other arguments given to the inline
attribute will return this error.
Example:
#[inline(never)] // ok!
pub fn something() {}
fn main() {}
RunFor more information see the inline
Attribute section
of the Reference.
The not
cfg-predicate was malformed.
Erroneous code example:
#[cfg(not())] // error: expected 1 cfg-pattern
pub fn something() {}
pub fn main() {}
RunThe not
predicate expects one cfg-pattern. Example:
#[cfg(not(target_os = "linux"))] // ok!
pub fn something() {}
pub fn main() {}
RunFor more information about the cfg
attribute, read the section on
Conditional Compilation in the Reference.
An unknown predicate was used inside the cfg
attribute.
Erroneous code example:
#[cfg(unknown())] // error: invalid predicate `unknown`
pub fn something() {}
pub fn main() {}
RunThe cfg
attribute supports only three kinds of predicates:
Example:
#[cfg(not(target_os = "linux"))] // ok!
pub fn something() {}
pub fn main() {}
RunFor more information about the cfg
attribute, read the section on
Conditional Compilation in the Reference.
Attribute contains same meta item more than once.
Erroneous code example:
#[deprecated(
since="1.0.0",
note="First deprecation note.",
note="Second deprecation note." // error: multiple same meta item
)]
fn deprecated_function() {}
RunMeta items are the key-value pairs inside of an attribute. Each key may only be used once in each attribute.
To fix the problem, remove all but one of the meta items with the same key.
Example:
#[deprecated(
since="1.0.0",
note="First deprecation note."
)]
fn deprecated_function() {}
RunAn invalid meta-item was used inside an attribute.
Erroneous code example:
#![feature(staged_api)]
#![stable(since = "1.0.0", feature = "test")]
#[rustc_deprecated(reason)] // error!
#[unstable(feature = "deprecated_fn", issue = "123")]
fn deprecated() {}
#[unstable(feature = "unstable_struct", issue)] // error!
struct Unstable;
#[rustc_const_unstable(feature)] // error!
const fn unstable_fn() {}
#[stable(feature = "stable_struct", since)] // error!
struct Stable;
#[rustc_const_stable(feature)] // error!
const fn stable_fn() {}
RunMeta items are the key-value pairs inside of an attribute. To fix these issues you need to give required key-value pairs.
#![feature(staged_api)]
#![stable(since = "1.0.0", feature = "test")]
#[rustc_deprecated(since = "1.39.0", reason = "reason")] // ok!
#[unstable(feature = "deprecated_fn", issue = "123")]
fn deprecated() {}
#[unstable(feature = "unstable_struct", issue = "123")] // ok!
struct Unstable;
#[rustc_const_unstable(feature = "unstable_fn", issue = "124")] // ok!
const fn unstable_fn() {}
#[stable(feature = "stable_struct", since = "1.39.0")] // ok!
struct Stable;
#[rustc_const_stable(feature = "stable_fn", since = "1.39.0")] // ok!
const fn stable_fn() {}
RunAn unknown meta item was used.
Erroneous code example:
#[deprecated(
since="1.0.0",
// error: unknown meta item
reason="Example invalid meta item. Should be 'note'")
]
fn deprecated_function() {}
RunMeta items are the key-value pairs inside of an attribute. The keys provided must be one of the valid keys for the specified attribute.
To fix the problem, either remove the unknown meta item, or rename it if you provided the wrong name.
In the erroneous code example above, the wrong name was provided, so changing to a correct one it will fix the error. Example:
#[deprecated(
since="1.0.0",
note="This is a valid meta item for the deprecated attribute."
)]
fn deprecated_function() {}
RunThe since
value is missing in a stability attribute.
Erroneous code example:
#![feature(staged_api)]
#![stable(since = "1.0.0", feature = "test")]
#[stable(feature = "_stable_fn")] // invalid
fn _stable_fn() {}
#[rustc_const_stable(feature = "_stable_const_fn")] // invalid
const fn _stable_const_fn() {}
#[stable(feature = "_deprecated_fn", since = "0.1.0")]
#[rustc_deprecated(
reason = "explanation for deprecation"
)] // invalid
fn _deprecated_fn() {}
RunTo fix this issue, you need to provide the since
field. Example:
#![feature(staged_api)]
#![stable(since = "1.0.0", feature = "test")]
#[stable(feature = "_stable_fn", since = "1.0.0")] // ok!
fn _stable_fn() {}
#[rustc_const_stable(feature = "_stable_const_fn", since = "1.0.0")] // ok!
const fn _stable_const_fn() {}
#[stable(feature = "_deprecated_fn", since = "0.1.0")]
#[rustc_deprecated(
since = "1.0.0",
reason = "explanation for deprecation"
)] // ok!
fn _deprecated_fn() {}
RunSee the How Rust is Made and “Nightly Rust” appendix of the Book and the Stability attributes section of the Rustc Dev Guide for more details.
The reason
value is missing in a stability attribute.
Erroneous code example:
#![feature(staged_api)]
#![stable(since = "1.0.0", feature = "test")]
#[stable(since = "0.1.0", feature = "_deprecated_fn")]
#[rustc_deprecated(
since = "1.0.0"
)] // invalid
fn _deprecated_fn() {}
RunTo fix this issue, you need to provide the reason
field. Example:
#![feature(staged_api)]
#![stable(since = "1.0.0", feature = "test")]
#[stable(since = "0.1.0", feature = "_deprecated_fn")]
#[rustc_deprecated(
since = "1.0.0",
reason = "explanation for deprecation"
)] // ok!
fn _deprecated_fn() {}
RunSee the How Rust is Made and “Nightly Rust” appendix of the Book and the Stability attributes section of the Rustc Dev Guide for more details.
Multiple stability attributes were declared on the same item.
Erroneous code example:
#![feature(staged_api)]
#![stable(since = "1.0.0", feature = "rust1")]
#[stable(feature = "rust1", since = "1.0.0")]
#[stable(feature = "test", since = "2.0.0")] // invalid
fn foo() {}
RunTo fix this issue, ensure that each item has at most one stability attribute.
#![feature(staged_api)]
#![stable(since = "1.0.0", feature = "rust1")]
#[stable(feature = "test", since = "2.0.0")] // ok!
fn foo() {}
RunSee the How Rust is Made and “Nightly Rust” appendix of the Book and the Stability attributes section of the Rustc Dev Guide for more details.
The issue
value is incorrect in a stability attribute.
Erroneous code example:
#![feature(staged_api)]
#![stable(since = "1.0.0", feature = "test")]
#[unstable(feature = "_unstable_fn", issue = "0")] // invalid
fn _unstable_fn() {}
#[rustc_const_unstable(feature = "_unstable_const_fn", issue = "0")] // invalid
const fn _unstable_const_fn() {}
RunTo fix this issue, you need to provide a correct value in the issue
field.
Example:
#![feature(staged_api)]
#![stable(since = "1.0.0", feature = "test")]
#[unstable(feature = "_unstable_fn", issue = "none")] // ok!
fn _unstable_fn() {}
#[rustc_const_unstable(feature = "_unstable_const_fn", issue = "1")] // ok!
const fn _unstable_const_fn() {}
RunSee the How Rust is Made and “Nightly Rust” appendix of the Book and the Stability attributes section of the Rustc Dev Guide for more details.
The feature
value is missing in a stability attribute.
Erroneous code example:
#![feature(staged_api)]
#![stable(since = "1.0.0", feature = "test")]
#[unstable(issue = "none")] // invalid
fn unstable_fn() {}
#[stable(since = "1.0.0")] // invalid
fn stable_fn() {}
RunTo fix this issue, you need to provide the feature
field. Example:
#![feature(staged_api)]
#![stable(since = "1.0.0", feature = "test")]
#[unstable(feature = "unstable_fn", issue = "none")] // ok!
fn unstable_fn() {}
#[stable(feature = "stable_fn", since = "1.0.0")] // ok!
fn stable_fn() {}
RunSee the How Rust is Made and “Nightly Rust” appendix of the Book and the Stability attributes section of the Rustc Dev Guide for more details.
The issue
value is missing in a stability attribute.
Erroneous code example:
#![feature(staged_api)]
#![stable(since = "1.0.0", feature = "test")]
#[unstable(feature = "_unstable_fn")] // invalid
fn _unstable_fn() {}
#[rustc_const_unstable(feature = "_unstable_const_fn")] // invalid
const fn _unstable_const_fn() {}
RunTo fix this issue, you need to provide the issue
field. Example:
#![feature(staged_api)]
#![stable(since = "1.0.0", feature = "test")]
#[unstable(feature = "_unstable_fn", issue = "none")] // ok!
fn _unstable_fn() {}
#[rustc_const_unstable(
feature = "_unstable_const_fn",
issue = "none"
)] // ok!
const fn _unstable_const_fn() {}
RunSee the How Rust is Made and “Nightly Rust” appendix of the Book and the Stability attributes section of the Rustc Dev Guide for more details.
A rustc_deprecated
attribute wasn’t paired with a stable
/unstable
attribute.
Erroneous code example:
#![feature(staged_api)]
#![stable(since = "1.0.0", feature = "test")]
#[rustc_deprecated(
since = "1.0.1",
reason = "explanation for deprecation"
)] // invalid
fn _deprecated_fn() {}
RunTo fix this issue, you need to add also an attribute stable
or unstable
.
Example:
#![feature(staged_api)]
#![stable(since = "1.0.0", feature = "test")]
#[stable(since = "1.0.0", feature = "test")]
#[rustc_deprecated(
since = "1.0.1",
reason = "explanation for deprecation"
)] // ok!
fn _deprecated_fn() {}
RunSee the How Rust is Made and “Nightly Rust” appendix of the Book and the Stability attributes section of the Rustc Dev Guide for more details.
More than one deprecated
attribute has been put on an item.
Erroneous code example:
#[deprecated(note = "because why not?")]
#[deprecated(note = "right?")] // error!
fn the_banished() {}
RunThe deprecated
attribute can only be present once on an item.
#[deprecated(note = "because why not, right?")]
fn the_banished() {} // ok!
RunAn invalid meta-item was used inside an attribute.
Erroneous code example:
#[deprecated(note)] // error!
fn i_am_deprecated() {}
RunMeta items are the key-value pairs inside of an attribute. To fix this issue,
you need to give a value to the note
key. Example:
#[deprecated(note = "because")] // ok!
fn i_am_deprecated() {}
RunA unrecognized representation attribute was used.
Erroneous code example:
#[repr(D)] // error: unrecognized representation hint
struct MyStruct {
my_field: usize
}
RunYou can use a repr
attribute to tell the compiler how you want a struct or
enum to be laid out in memory.
Make sure you’re using one of the supported options:
#[repr(C)] // ok!
struct MyStruct {
my_field: usize
}
RunFor more information about specifying representations, see the “Alternative Representations” section of the Rustonomicon.
Feature attributes are only allowed on the nightly release channel. Stable or beta compilers will not comply.
Erroneous code example:
#![feature(lang_items)] // error: `#![feature]` may not be used on the
// stable release channel
RunIf you need the feature, make sure to use a nightly release of the compiler (but be warned that the feature may be removed or altered in the future).
The feature
attribute was badly formed.
Erroneous code example:
#![feature(foo_bar_baz, foo(bar), foo = "baz", foo)] // error!
#![feature] // error!
#![feature = "foo"] // error!
RunThe feature
attribute only accept a “feature flag” and can only be used on
nightly. Example:
#![feature(flag)]
RunA feature attribute named a feature that has been removed.
Erroneous code example:
#![feature(managed_boxes)] // error: feature has been removed
RunDelete the offending feature attribute.
An unknown field was specified into an enum’s structure variant.
Erroneous code example:
enum Field {
Fool { x: u32 },
}
let s = Field::Fool { joke: 0 };
// error: struct variant `Field::Fool` has no field named `joke`
RunVerify you didn’t misspell the field’s name or that the field exists. Example:
enum Field {
Fool { joke: u32 },
}
let s = Field::Fool { joke: 0 }; // ok!
RunAn unknown field was specified into a structure.
Erroneous code example:
struct Simba {
mother: u32,
}
let s = Simba { mother: 1, father: 0 };
// error: structure `Simba` has no field named `father`
RunVerify you didn’t misspell the field’s name or that the field exists. Example:
struct Simba {
mother: u32,
father: u32,
}
let s = Simba { mother: 1, father: 0 }; // ok!
RunA non-ident or non-wildcard pattern has been used as a parameter of a function pointer type.
Erroneous code example:
type A1 = fn(mut param: u8); // error!
type A2 = fn(¶m: u32); // error!
RunWhen using an alias over a function type, you cannot e.g. denote a parameter as being mutable.
To fix the issue, remove patterns (_
is allowed though). Example:
type A1 = fn(param: u8); // ok!
type A2 = fn(_: u32); // ok!
RunYou can also omit the parameter name:
type A3 = fn(i16); // ok!
RunAbstract return types (written impl Trait
for some trait Trait
) are only
allowed as function and inherent impl return types.
Erroneous code example:
fn main() {
let count_to_ten: impl Iterator<Item=usize> = 0..10;
// error: `impl Trait` not allowed outside of function and inherent method
// return types
for i in count_to_ten {
println!("{}", i);
}
}
RunMake sure impl Trait
only appears in return-type position.
fn count_to_n(n: usize) -> impl Iterator<Item=usize> {
0..n
}
fn main() {
for i in count_to_n(10) { // ok!
println!("{}", i);
}
}
RunSee RFC 1522 for more details.
A literal was used in a built-in attribute that doesn’t support literals.
Erroneous code example:
#[repr("C")] // error: meta item in `repr` must be an identifier
struct Repr {}
fn main() {}
RunLiterals in attributes are new and largely unsupported in built-in attributes. Work to support literals where appropriate is ongoing. Try using an unquoted name instead:
#[repr(C)] // ok!
struct Repr {}
fn main() {}
RunConflicting representation hints have been used on a same item.
Erroneous code example:
#[repr(u32, u64)]
enum Repr { A }
RunIn most cases (if not all), using just one representation hint is more than
enough. If you want to have a representation hint depending on the current
architecture, use cfg_attr
. Example:
#[cfg_attr(linux, repr(u32))]
#[cfg_attr(not(linux), repr(u64))]
enum Repr { A }
RunGenerics have been used on an auto trait.
Erroneous code example:
#![feature(auto_traits)]
auto trait Generic<T> {} // error!
RunSince an auto trait is implemented on all existing types, the compiler would not be able to infer the types of the trait’s generic parameters.
To fix this issue, just remove the generics:
#![feature(auto_traits)]
auto trait Generic {} // ok!
RunA super trait has been added to an auto trait.
Erroneous code example:
#![feature(auto_traits)]
auto trait Bound : Copy {} // error!
fn main() {}
RunSince an auto trait is implemented on all existing types, adding a super trait
would filter out a lot of those types. In the current example, almost none of
all the existing types could implement Bound
because very few of them have the
Copy
trait.
To fix this issue, just remove the super trait:
#![feature(auto_traits)]
auto trait Bound {} // ok!
fn main() {}
RunIf an impl has a generic parameter with the #[may_dangle]
attribute, then
that impl must be declared as an unsafe impl
.
Erroneous code example:
#![feature(dropck_eyepatch)]
struct Foo<X>(X);
impl<#[may_dangle] X> Drop for Foo<X> {
fn drop(&mut self) { }
}
RunIn this example, we are asserting that the destructor for Foo
will not
access any data of type X
, and require this assertion to be true for
overall safety in our program. The compiler does not currently attempt to
verify this assertion; therefore we must tag this impl
as unsafe.
The requested ABI is unsupported by the current target.
The rust compiler maintains for each target a list of unsupported ABIs on that target. If an ABI is present in such a list this usually means that the target / ABI combination is currently unsupported by llvm.
If necessary, you can circumvent this check using custom target specifications.
A break
statement with an argument appeared in a non-loop
loop.
Example of erroneous code:
let result = while true {
if satisfied(i) {
break 2 * i; // error: `break` with value from a `while` loop
}
i += 1;
};
RunThe break
statement can take an argument (which will be the value of the loop
expression if the break
statement is executed) in loop
loops, but not
for
, while
, or while let
loops.
Make sure break value;
statements only occur in loop
loops:
let result = loop { // This is now a "loop" loop.
if satisfied(i) {
break 2 * i; // ok!
}
i += 1;
};
RunA return statement was found outside of a function body.
Erroneous code example:
const FOO: u32 = return 0; // error: return statement outside of function body
fn main() {}
RunTo fix this issue, just remove the return keyword or move the expression into a function. Example:
const FOO: u32 = 0;
fn some_fn() -> u32 {
return FOO;
}
fn main() {
some_fn();
}
RunSomething other than a type has been used when one was expected.
Erroneous code examples:
enum Dragon {
Born,
}
fn oblivion() -> Dragon::Born { // error!
Dragon::Born
}
const HOBBIT: u32 = 2;
impl HOBBIT {} // error!
enum Wizard {
Gandalf,
Saruman,
}
trait Isengard {
fn wizard(_: Wizard::Saruman); // error!
}
RunIn all these errors, a type was expected. For example, in the first error, if
we want to return the Born
variant from the Dragon
enum, we must set the
function to return the enum and not its variant:
enum Dragon {
Born,
}
fn oblivion() -> Dragon { // ok!
Dragon::Born
}
RunIn the second error, you can’t implement something on an item, only on types. We would need to create a new type if we wanted to do something similar:
struct Hobbit(u32); // we create a new type
const HOBBIT: Hobbit = Hobbit(2);
impl Hobbit {} // ok!
RunIn the third case, we tried to only expect one variant of the Wizard
enum,
which is not possible. To make this work, we need to using pattern matching
over the Wizard
enum:
enum Wizard {
Gandalf,
Saruman,
}
trait Isengard {
fn wizard(w: Wizard) { // ok!
match w {
Wizard::Saruman => {
// do something
}
_ => {} // ignore everything else
}
}
}
RunSomething other than a struct, variant or union has been used when one was expected.
Erroneous code example: