about summary refs log tree commit diff
path: root/compiler/rustc_error_codes/src/error_codes/E0804.md
blob: 9a6937c0b52e03797060e3b5d3fbd46451f2b0dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
An auto trait cannot be added to the bounds of a `dyn Trait` type via
a pointer cast.

Erroneous code example:

```rust,edition2021,compile_fail,E0804
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:

```rust,edition2021,no_run
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.