2

I want to have a method to_holder of SomeTrait that'll store reference to the trait object to a struct, but the compiler forces Self of method to_holder to be Sized. Annotating Self: Sized does work, but that way I can't call to_holder from a trait object, which is troubling.

Here's the code:


trait SomeTrait {
    type Item;

    fn to_holder(&self) -> TraitObjectHolder<Self::Item> {
        TraitObjectHolder { obj: self }
    }
}

struct TraitObjectHolder<'a, T> {
    obj: &'a dyn SomeTrait<Item=T>,
}

struct SomeStruct<T> {
    item: T
}

impl<T> SomeTrait for SomeStruct<T> {
    type Item = T;
}

fn main() {
    let some_struct = SomeStruct { item: 0 };
    let some_struct = &some_struct as &dyn SomeTrait<Item=i32>;
    some_struct.to_holder();
}

And here's the compiler error:


error[E0277]: the size for values of type `Self` cannot be known at compilation time
 --> src/main.rs:5:34
  |
5 |         TraitObjectHolder { obj: self }
  |                                  ^^^^ doesn't have a size known at compile-time
  |
  = note: required for the cast from `Self` to the object type `dyn SomeTrait<Item = <Self as SomeTrait>::Item>`
help: consider further restricting `Self`
  |
4 |     fn to_holder(&self) -> TraitObjectHolder<Self::Item> where Self: Sized {
  |                                                          +++++++++++++++++

For more information about this error, try `rustc --explain E0277`.

I wonder that I'm just passing around references here, what does that has to do with whether Self is Sized?

Actually, it seems if I don't use associated function, things will be fine


fn to_holder<T>(x: &dyn SomeTrait<Item=T>) -> TraitObjectHolder<T> {
    TraitObjectHolder { obj: x }
}

Think you might need it, I'll also mention a bit of my original problem .

I'm writing a toy matrix calculating library, there is a trait Mat and many concrete types that implements Mat, for example, a DataMatrix holding the data and a SliceMatrix referring to slice of whatever matrix type that implements Mat.

Now, I want a method on Mat called row that returns a SliceMatrix referring to a row of that Mat trait object, but rust just doesn't allow me to call row on a trait object.

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
danzou1ge6
  • 53
  • 2

0 Answers0