Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
795 views
in Technique[技术] by (71.8m points)

rust - Why can a trait not construct itself?

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)?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...