Working with Self in dyn-compatible trait objects
⚓ Rust 📅 2025-08-04 👤 surdeus 👁️ 10Hello. I’m still somewhat of a beginner, so forgive me if this is a simple question, but I can attest that I’ve exhausted all sources I could find on the matter and am still not precisely sure how to tackle it.
I’ve been playing around with dynamic dispatch, and have ran into a bit of an odd dilemma.
While the lines…
trait BasicTrait {
fn foo(self: Box<Self>) -> Box<dyn BasicTrait>;
}
struct BasicStruct;
impl BasicTrait for BasicStruct {
fn foo(self: Box<Self>) -> Box<dyn BasicTrait> {
self
}
}
…compile perfectly fine,
The lines…
trait BasicTrait {
fn foo(self: Box<Self>) -> Box<dyn BasicTrait> {
self
}
}
struct BasicStruct;
impl BasicTrait for BasicStruct {}
…refuse to compile, throwing the error “self doesn't have a size known at compile-time".
I can roughly understand why - as I understand it, “self” in the trait declaration refers to the dynamically dispatched trait object, while “self” in the impl refers to the more concrete struct implementing the trait. However, (assuming I am understanding the inner workings correctly) is there any way around this? Ideally, I’d like to have a function that features the type signature of foo in my above example, but wouldn’t need to be manually implemented by anything implementing the trait.
1 post - 1 participant
🏷️ Rust_feed