rust - 为什么特质不能 self 构建?

标签 rust

这段代码给我一个编译错误:

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

虽然这段代码编译没有任何错误:

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

trait IFoo {
    fn new() -> Box<IBoo>;
}
  1. 为什么第一个不编译? rustc --explain E0038 没有直接提示我为什么不可能。
  2. 是否可以将构造和方法组合在一个接口(interface)(特征)中?

最佳答案

这是来自 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;
}

你可以这样做:

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

在其他情况下,您可以对整个 impl 进行限制:

关于rust - 为什么特质不能 self 构建?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38159771/

相关文章:

rust - 保存文件后, cargo 测试会警告未使用的代码

rust - 使用 Hyper 为 GET 请求传递数据

json - 以不同的格式反序列化 JSON - Serde_JSON

generics - `std::ops::Fn<(char,)>` 未实现特征 `T`

rust - 无法释放文件。收到错误 : could not compile 'libc'

rust - 在 `loop` 中使用 Rust 的错误会导致廉价的阻塞,但为什么呢?

rust - 为什么 `tokio::main` 报告错误 "cycle detected when processing"?

rust - 如何在 Rust 的内联汇编宏中使用常量?

Rust 函数名称(调用者)或宏内的任何其他上下文

rust - Rust的确切自动引用规则是什么?