【发布时间】:2021-01-20 17:42:24
【问题描述】:
我有多个级别的特征,不知道如何引用顶级对象中的类型。我收到有关未使用参数的消息,但如果我删除它们,我会收到有关它们丢失的消息!一个例子:
struct User {
name: String,
}
trait UserStore {
fn get_user(&self) -> User;
}
struct Tenant<U>
where
U: UserStore,
{
user_store: U,
}
trait TenantStore<U>
where
U: UserStore
{
fn get_tenant(&self) -> Tenant<U>;
}
// what to do here??
struct Application<T, U>
where
T: TenantStore<U>,
U: UserStore
{
tenant_store: T,
}
错误:
parameter `U` is never used
unused parameter
help: consider removing `U`, referring to it in a field, or using a marker such as `std::marker::PhantomData`rustc(E0392)
如果我删除 U 我会得到:
cannot find type `U` in this scope
【问题讨论】:
-
我打赌你想要一个关联类型而不是类型参数。见Struct with a generic trait which is also a generic trait
-
That answer applied here。虽然我建议从
structs 中删除where子句;它们似乎没有任何用途。 -
@trentcl 看起来关联类型可能是我所追求的。但是结构上的
where子句难道不是为了限制泛型参数的类型吗?例如,我不想拥有Tenant<i32>。还是我错过了什么? -
结构上的特征边界通常仅在 结构定义本身 以某种方式使用该特征时才有用。例如,
std::iter::Peekable<I: Iterator>包含一个I::Item,因此删除I: Iterator绑定显然无法编译。当 trait 没有在结构本身中使用,而仅在定义其行为的impl块中使用时,仅将绑定添加到需要它的impl块中的冗余较少...... -
... 就像在
std::collections::HashMap<K, V, S>中一样,它不会将K与Eq + Hash或S与BuildHasher绑定,但在定义使用这些特征的方法的impl块中除外.毕竟,如果有人假设Tenant<i32>有用,那么阻止他们真的很重要吗?在实现implied bounds 之前,在Tenant<U>上添加边界(IMO)只是浪费打字。impl块的边界就足够了。