rust - 为什么在将更高等级的特征边界与关联类型结合时会出现 Rust 编译错误?
问题描述
我正在编写一些涉及泛型特征和非'static
类型的 Rust 代码,因此我遇到了近似泛型关联类型的需求。我知道在当前的 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
doesn't implement Debug
,这没有意义。我一定是误解了错误消息的含义,但我无法弄清楚实际问题是什么。
解决方案
关于这个问题有一个未解决的问题。
在您的情况下,解决方法可能是绑定Debug
到关联类型Resource::Value
?
trait Resource<'r> {
type Value: Debug;
}.
推荐阅读
- javascript - 如何在 Shopify 中延迟 theme.liquid 中的 javascript 文件
- javascript - 使用 paper.js 在画布顶部下方绘制 1/4 段
- javascript - axios react js自动取消请求
- bash - 如何在 Perl 中使用 Shell 参数扩展?
- php - 在 CPanel 的 Laravel 项目中找不到 Twilio MessagingResponse 类
- reactjs - 反应js基于按钮点击渲染不同的组件
- pycharm - 无法在 Pycharm 中设置条件断点
- javascript - 将参数传递给父组件中的函数
- javascript - 使用 window.prompt() 通过 JavaScript 添加列表项
- data-structures - 哈希表中的负载因子和时间复杂度之间的关系?