为什么将高阶特征范围与关联类型结合在一起时为什么会出现Rust编译错误?

问题描述 投票:2回答:1

我正在编写一些涉及泛型特征和非'static类型的Rust代码,结果我遇到了近似generic associated types的需求。我知道在当前的Rust中不能很好地模拟GAT,但是我认为我已经找到了(无意义的)解决方法,该方法适用于我的特定情况,使用具有生存期参数和较高等级特征范围的特征。但是,由于缺少关联类型的特征实现,我遇到了我不理解的编译器错误。

以下代码显示了重现该错误的最小示例。

use std::fmt::Debug;

trait Resource<'r> {
    type Value;
}

struct ResourceImpl();

impl<'r> Resource<'r> for ResourceImpl {
    type Value = u32;
}

fn test_generic<R>()
where
    for<'r> R: Resource<'r>,
    for<'r> <R as Resource<'r>>::Value: Debug,
{
}

fn test_specific() {
    test_generic::<ResourceImpl>();
}

[当我尝试编译此代码(rustc 1.41.0)时,收到以下错误消息。

error[E0277]: `<ResourceImpl as Resource<'r>>::Value` doesn't implement `std::fmt::Debug`
  --> src/lib.rs:21:5
   |
13 | fn test_generic<R>()
   |    ------------
...
16 |     for<'r> <R as Resource<'r>>::Value: Debug,
   |                                         ----- required by this bound in `test_generic`
...
21 |     test_generic::<ResourceImpl>();
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `<ResourceImpl as Resource<'r>>::Value` cannot be formatted using `{:?}` because it doesn't implement `std::fmt::Debug`
   |
   = help: the trait `for<'r> std::fmt::Debug` is not implemented for `<ResourceImpl as Resource<'r>>::Value`

错误消息听起来像是在说u32没有实现Debug,这没有任何意义。我一定会误解错误消息的含义,但是我无法弄清楚实际的问题是什么。

更新:除了此问题的公认答案中提到的解决方法,在链接GitHub issue的讨论中还提到了另一种可能的解决方法。在this Stack Overflow question的答案中对此进行了描述。

rust
1个回答
2
投票

关于此问题有open issue

在您的情况下,一种解决方法是将Debug绑定到关联的类型Resource::Value

trait Resource<'r> {
    type Value: Debug;
}.
© www.soinside.com 2019 - 2024. All rights reserved.