Warning
This post was published 31 days ago. The information described in this article may have changed.
Returning an owned "dyn" object without heap allocations
โ Rust ๐ 2025-08-05 ๐ค surdeus ๐๏ธ 5Hello.
Is it possible to return an owned dyn Trait
from a function without using heap-allocations, like Box or Arc?
In my case, the types implementing Trait
are expected to be small, no more than N bytes, so I thought maybe it would be possible to return a type that reserves the needed N bytes, and stores a pointer to the dyn vtable, like so (just a high-level sketch):
trait MyTrait {}
struct MyType; // this is no more than 16 bytes
impl MyTrait for MyType {}
struct OnStack<T, const N: usize> {
vtable: *mut T::Vtable,
data: [u8; N],
}
fn my_function() -> OnStack<dyn MyTrait, 16> {
OnStack::new(MyType::new()).expect("MyType is larger than 16 bytes")
}
Rust already uses space reservation for enums: the size of an enum is determined by the size of its largest variant. So maybe itโs also possible to do for other types with variable size, like `dyn Trait`?
Thanks!
4 posts - 3 participants
๐ท๏ธ Rust_feed