When would a method need `Self` to be `Sized`
⚓ Rust 📅 2026-03-07 👤 surdeus 👁️ 2I am learning Sized Trait and Trait Object, and there is a rule that if I want to create a trait object,
Sized must not be a supertrait. In other words, it must not require Self: Sized.
many resources have tell me that a trait method that returns Self needs the Trait to be Sized. What's more? Is there a rule that can determine a method or a trait should be `Sized?
here is a example that cannot be compiled:
trait SizedTrait {
fn get_self(self) -> Self;
}
struct MyStruct {}
impl SizedTrait for MyStruct {
fn get_self(self) -> Self {
MyStruct {}
}
}
struct OtherStruct {}
impl SizedTrait for OtherStruct {
fn get_self(self) -> Self {
OtherStruct {}
}
}
fn main() {
let x = MyStruct {};
let y = OtherStruct {};
let v = vec![&x as &dyn SizedTrait, &y as &dyn SizedTrait];
for i in v {
i.print_self();
}
}
2 posts - 2 participants
🏷️ Rust_feed