Why casting *mut T to *mut dyn Trait requires T: Sized?

⚓ Rust    📅 2025-08-06    👤 surdeus    👁️ 5      

surdeus

Hello.

This code fails to compile:

trait MyTrait {}

fn convert<T: ?Sized + MyTrait + 'static>(v: *mut T) -> *mut dyn MyTrait {
    v
}

With an error:

error[E0277]: the size for values of type `T` cannot be known at compilation time
 --> src/main.rs:4:5
  |
3 | fn convert<T: ?Sized + MyTrait + 'static>(v: *mut T) -> *mut dyn MyTrait {
  |            - this type parameter needs to be `Sized`
4 |     v
  |     ^ doesn't have a size known at compile-time
  |
  = note: required for the cast from `*mut T` to `*mut (dyn MyTrait + 'static)`
help: consider removing the `?Sized` bound to make the type parameter `Sized`

I thought that to create a wide pointer the compiler needs to know only pointer to data and pointer to vtable, and I think the compiler knows both. Also I think `v` has known compile-time size, since it is a pointer, and all pointers have known compile-time size. Then why does the compiler require T to be Sized?

Thanks!

2 posts - 2 participants

Read full topic

🏷️ Rust_feed