Email me

Rust errors / Types and traits

Rust compiler error · checked with rustc 1.99.0

Rust error E0804: cannot add auto trait `Send` to dyn bound via pointer cast

What it meansAn auto trait cannot be added to the bounds of a dyn Trait type via a pointer cast.

What rustc prints

error[E0804]: cannot add auto trait `Send` to dyn bound via pointer cast
 --> main.rs:4:5
  |
4 | _ = ptr as *const (dyn core::any::Any + Send);
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unsupported cast
  |
  = note: this could allow UB elsewhere
  = help: use `transmute` if you're sure this is sound

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.

E0804Types and traits
Activein rustc 1.99.0
7related errors linked below

The compiler team's explanation

An auto trait cannot be added to the bounds of a dyn Trait type via a pointer cast.

Erroneous code example:

let ptr: *const dyn core::any::Any = &();
_ = ptr as *const (dyn core::any::Any + Send);

Adding an auto trait can make the vtable invalid, potentially causing UB in safe code afterwards. For example:

use core::{mem::transmute, ptr::NonNull};

trait Trait {
    fn f(&self)
    where
        Self: Send;
}

impl Trait for NonNull<()> {
    fn f(&self) {
        unreachable!()
    }
}

fn main() {
    let unsend: &dyn Trait = &NonNull::dangling();
    let bad: &(dyn Trait + Send) = unsafe { transmute(unsend) };
    // This crashes, since the vtable for `NonNull as dyn Trait` does
    // not have an entry for `Trait::f`.
    bad.f();
}

To fix this error, you can use transmute rather than pointer casts, but you must ensure that the vtable is valid for the pointer's type before calling a method on the trait object or allowing other code to do so.

From rustc --explain E0804 (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 nextE0308: mismatched typesA 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