Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can a trait not construct itself?

Tags:

rust

This code give me a compilation error:

trait IBoo {
    fn new() -> Box<IBoo>;
}

while this code compiles without any error:

trait IBoo {
    //fn new() -> Box<IBoo>;
}

trait IFoo {
    fn new() -> Box<IBoo>;
}
  1. Why does the first one not compile? rustc --explain E0038 does not give me a direct hint why it is not possible.
  2. Is it possible to combine construction and methods in one interface (trait)?
like image 411
user1244932 Avatar asked Jul 02 '16 11:07

user1244932


People also ask

What is trait theory and personal construct?

Trait theory and personal construct. Trait theory is widely understood due to its similarities to how people assess others in everyday life (Butt,2007). In addition to this, measurement tools, such as the EPI, are objective measures of personality, allowing comparisons to be drawn between large samples of individuals.

What are the advantages of trait theory?

Since trait theory is largely based on statistical data, it removes any bias influence and remains objective, unlike other personality theories, which are based on subjective personal experiences. Furthermore, it is a clear and easy to apply approach for use in understanding people.

Is it possible to add self constraints to individual trait methods?

I didn't realise it was possible to add Self constraints to individual trait methods. I had thought constraints had to be on the trait itself, and that this sort of problem could only be approached by breaking the trait up. Thanks for writing this up; I completely forgot about that. – DK. More detail about Self: Sized, go! Note the last line.

What are the limitations of trait theory?

The principles of trait theory mean it does not recognise potential for change, as traits are biologically controlled. This limits its ability to be used to assist change, so this is a less practical approach than PCT. Another major criticism is that causation cannot be inferred by correlation alone.


1 Answers

This is from the description of E0038:

Method has no receiver

Methods that do not take a self parameter can't be called since there won't be a way to get a pointer to the method table for them.

trait Foo {
    fn foo() -> u8;
}

This could be called as <Foo as Foo>::foo(), which would not be able to pick an implementation.

Adding a Self: Sized bound to these methods will generally make this compile.

trait Foo {
    fn foo() -> u8 where Self: Sized;
}

You can do this:

trait IBoo {
    fn new() -> Box<IBoo>
    where
        Self: Sized;
}

In other cases, you can place the restriction on the entire impl:

like image 186
aSpex Avatar answered Oct 02 '22 08:10

aSpex