Rust errors / Ownership and borrowing
Rust compiler error · checked with rustc 1.99.0
Rust error E0161: cannot move a value of type `dyn Bar`
What it meansA value was moved whose size was not known at compile time.
What rustc prints
error[E0161]: cannot move a value of type `dyn Bar`
--> main.rs:11:5
|
11 | b.f();
| ^ the size of `dyn Bar` cannot be statically determinedReal output of rustc 1.99.0 compiling the official example below (2021 edition). Your names and line numbers will differ; the first line is the part to match.
The compiler team's explanation
A value was moved whose size was not known at compile time.
Erroneous code example:
trait Bar {
fn f(self);
}
impl Bar for i32 {
fn f(self) {}
}
fn main() {
let b: Box<dyn Bar> = Box::new(0i32);
b.f();
// error: cannot move a value of type dyn Bar: the size of dyn Bar cannot
// be statically determined
}
In 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:
trait Bar {
fn f(&self);
}
impl Bar for i32 {
fn f(&self) {}
}
fn main() {
let b: Box<dyn Bar> = Box::new(0i32);
b.f();
// ok!
}From rustc --explain E0161 (1.99.0), part of the Rust project, MIT or Apache-2.0. Official page.
Related errors
- E0382borrow of moved value
- E0499cannot borrow as mutable more than once at a time
- E0502cannot borrow as mutable because it is also borrowed as immutable
- E0106missing lifetime specifier
- E0195lifetime parameters do not match the trait definition
- E0207the type parameter `T` is not constrained by the impl trait, self type, or predicates
Up next
Often hit nextE0382: borrow of moved valueA related error from the same family.Read it next →Did this answer your question?