我遇到了一个问题,我将其简化为以下代码:
trait Logger {}
struct DefaultLogger;
impl Logger for DefaultLogger {}
struct A<L> where L: Logger {
logger: Box<L>,
}
impl<L> A<L> where L: Logger {
fn new() -> Self {
let logger = DefaultLogger;
A {
logger: Box::new(logger),
// ^^^^^^ Here is the problem
}
}
}
fn main() {
let a = A::new();
}
会产生以下错误:
error[E0308]: mismatched types
--> src/main.rs:16:30
|
16 | logger: Box::new(logger),
| ^^^^^^ expected type parameter, found struct `DefaultLogger`
|
= note: expected type `L`
found type `DefaultLogger`
当我在正常函数(如A
)中构造特征main
时,就像我预期的那样。例如:
trait Logger {}
struct DefaultLogger;
impl Logger for DefaultLogger {}
struct A<L> where L: Logger {
logger: Box<L>,
}
fn main() {
let logger = DefaultLogger;
let _a = A {
logger: Box::new(logger),
};
}
答案 0 :(得分:1)
问题在于:
impl<L> A<L> where L: Logger {
fn new() -> Self {
let logger = DefaultLogger;
A {
logger: Box::new(logger),
}
}
}
您想要返回A<L>
,但是如果您无法确定A<DefaultLogger>
,则会返回L == DefaultLogger
。
要解决此问题,您可以提供仅为A::new
创建方法DefaultLogger
的专门化:
impl A<DefaultLogger> {
fn new() -> Self {
let logger = DefaultLogger;
A {
logger: Box::new(logger),
}
}
}