期望的类型参数,找到struct

时间:2017-07-22 11:02:25

标签: rust traits

我遇到了一个问题,我将其简化为以下代码:

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),
        };
}

1 个答案:

答案 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),
        }
    }
}