当调用一个不需要的特征的默认实现时self
,为什么需要注释一个实现类型呢?
A 最小的、可重现的例子在下面 (操场):
mod builder {
pub trait Builder: Sized {
fn new() -> Simple {
Simple
}
}
pub struct Simple;
impl Builder for Simple {}
}
pub fn main() {
let _ = builder::Builder::new();
/* Working version */
// use builder::Builder;
// let _ = builder::Simple::new();
}
这使:
error[E0283]: type annotations needed
--> src/main.rs:14:13
|
3 | fn new() -> Simple {
| ------------------ required by `builder::Builder::new`
...
14 | let _ = builder::Builder::new();
| ^^^^^^^^^^^^^^^^^^^^^ cannot infer type
|
= note: cannot satisfy `_: builder::Builder`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0283`.
error: could not compile `playground`.
To learn more, run the command again with --verbose.
编译器的解释为E0283
没有提到默认实现,我同意这是有道理的。但对于默认实现,为什么需要类型?
这不仅是一个默认实现但是非常具体的案例其中这个默认实现甚至没有提到Self
/self
在它的参数、结果和主体中。
我发现更容易理解一条规则,即每次我们使用特征时都需要一个类型,无论如何,而不是« 除非默认实现甚至没有提及Self
/self
其参数、结果和主体 ».
对于这个非常具体的用例,您不想在调用所需函数时显式命名类型,我建议使用自由函数。
mod builder {
// ...
pub fn make_default() -> Simple {
Simple
}
// ...
}
pub fn main() {
let _ = builder::make_default();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)