Row size does not depend on size

The following code compiles:

trait SizedTrait: Sized { fn me() -> Self; } trait AnotherTrait: Sized { fn another_me() -> Self; } 

But the following code does not:

 impl AnotherTrait for SizedTrait { fn another_me() { Self::me() } } 

And gives the following errors:

 error[E0277]: the trait bound `SizedTrait + 'static: std::marker::Sized` is not satisfied --> src/main.rs:9:6 | 9 | impl AnotherTrait for SizedTrait { | ^^^^^^^^^^^^ `SizedTrait + 'static` does not have a constant size known at compile-time | = help: the trait `std::marker::Sized` is not implemented for `SizedTrait + 'static` error[E0038]: the trait `SizedTrait` cannot be made into an object --> src/main.rs:9:6 | 9 | impl AnotherTrait for SizedTrait { | ^^^^^^^^^^^^ the trait `SizedTrait` cannot be made into an object | = note: the trait cannot require that `Self : Sized` 

Why do both traits return self , but can I not implement one trait using the other? How to solve this problem without using a limited type parameter?

This is different from the Creator that implements Sized , because the return of self is legal (for the Sized attribute), and the return of any other trait is not.

0
source share
2 answers

As indicated by Shepmaster , you are trying to implement a trait for another trait, which is not possible.

What you really want (if I assume correctly) when you implement SizedTrait , AnotherTrait should also be implemented implicitly for this type. This can be done as follows:

 impl<T> AnotherTrait for T where T: SizedTrait, { fn another_me() -> Self { Self::me() } } 

Now that you are implementing SizedTrait , AnotherTrait automatically implemented for this type.

 struct Dummy; impl SizedTrait for Dummy { fn me() -> Self { Dummy } } fn main() { Dummy::me(); Dummy::another_me(); } 

Playground

If you really need to be explicit, you can also write

 impl<T> AnotherTrait for T where T: SizedTrait, { fn another_me() -> Self { <Self as SizedTrait>::me() } } 
0
source

As I understand the answer referenced by @Shepmaster, the implementation for AnotherTrait does not return an object that implemented SizedTrait , but another object created specifically for this case (an object object that contains a link to an object that implements this attribute ).

I don’t want to return an attribute object, and I assume that is why it does not implement Sized : so that I do not do what I did not want to do.

-1
source

Source: https://habr.com/ru/post/1276297/


All Articles