我有以下示例代码:
trait Manager: Sized {
type Item: Item<Manager=Self>;
}
trait Item: Sized {
type Manager: Manager<Item=Self> = DefaultManager<Self>;
}
struct DefaultManager<T: Item<Manager=DefaultManager<T>>>(::std::marker::PhantomData<T>);
impl<T: Item<Manager=DefaultManager<T>>> Manager for DefaultManager<T> {
type Item = T;
}
产生警告(以及将来的错误):
<anon>:9:5: 9:61 warning: type mismatch resolving `<Self as Item>::Manager == DefaultManager<Self>`: expected associated type, found struct `DefaultManager` [E0271]
<anon>:9 type Manager: Manager<Item=Self> = DefaultManager<Self>;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<anon>:9:5: 9:61 help: see the detailed explanation for E0271
<anon>:9:5: 9:61 note: this warning results from recent bug fixes and clarifications; it will become a HARD ERROR in the next release. See RFC 1214 for details.
<anon>:9 type Manager: Manager<Item=Self> = DefaultManager<Self>;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<anon>:9:5: 9:61 note: required by `DefaultManager`
我的问题是类型不匹配来自哪里?该警告突出显示了Item::Manager
的默认值,但指出要破坏的类型要求来自DefaultManager
。如果我删除Item::Manager
的默认值,则警告消失,但我更喜欢保留默认值。改变
struct DefaultManager<T: Item<Manager=DefaultManager<T>>>(...)
到
struct DefaultMananger<T: Item>
(但保留Manager
DefaultManager
impl上的关联类型约束也会清除警告,但可能不太理想,因为它会允许发生类似以下内容:
struct Foo;
impl Item for Foo { type Manager = FooManager; }
struct FooManager;
impl Manager for FooManager { type Item = Foo; }
type DefaultFooManager = DefaultManager<Foo>;
在这种情况下,DefaultManager<Foo>
不应该是有效类型,因为<Foo as Item>::Manager
是FooManager
,而不是DefaultManager<Foo>
。
导致类型不匹配的原因是什么?我如何向编译器澄清是否满足类型约束?
编辑:为了澄清,我使用了不稳定的associated_type_defaults
功能,以便我可以为Item::Manager
提供默认值,因此此示例仅在此时每晚构建。