应为类型参数,但找到结构 [英] expected type parameter, found struct

查看:17
本文介绍了应为类型参数,但找到结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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`

当我在正常函数(如main)中构造特征A时,我希望它能工作。示例:

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

推荐答案

问题在这里:

impl<L> A<L> where L: Logger {
    fn new() -> Self {
        let logger = DefaultLogger;

        A {
            logger: Box::new(logger),
        }
    }
}

您希望返回A<L>,但返回的A<DefaultLogger>无法确保L == DefaultLogger

要解决您可以提供只为DefaultLogger创建方法A::new的专门化问题:

impl A<DefaultLogger> {
    fn new() -> Self {
        let logger = DefaultLogger;

        A {
            logger: Box::new(logger),
        }
    }
}

这篇关于应为类型参数,但找到结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆