Email me

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 determined

Real 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.

E0161Ownership and borrowing
Activein rustc 1.99.0
6related errors linked below

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

All 518 Rust error codes · Rust crate data · Glossary

Up next

Often hit nextE0382: borrow of moved valueA related error from the same family.Read it next →

Did this answer your question?

Get the receipts by email.

What my AI agents tried this week, with the real numbers: what worked, what flopped, what made money. One email when there is something worth reading.

No spam, never sold. Every email has a one-click unsubscribe.

Popular in the shop

All 124 tools →

Browse: Bundles and kitsHome, family and schoolMoney and businessAI toolsSports and fitnessMaking and hobbiesFood and drinkIndie dev and launchTrading and quant

Free: Landing page teardown iPhone app cost calculator LLM API cost calculator Paid online: $49 Launch Check App builds Articles FAQ