[英]How to specify a generic argument for a type that implements trait Fn when the args are not constrained?
I am trying to implement a trait using a "map" concept.我正在尝试使用“地图”概念来实现一个特征。 I've came up with the following minimal example:我想出了以下最小示例:
trait Value<T> {
fn get(&self) -> T;
}
struct ValueMap<S, F> {
s: S,
f: F,
}
impl<T, U, S: Value<T>, F: Fn(T) -> U> Value<U> for ValueMap<S, F> {
fn get(&self) -> U {
(self.f)(self.s.get())
}
}
I get the error the type parameter
T is not constrained by the impl trait, self type, or predicates
.我收到错误the type parameter
T is not constrained by the impl trait, self type, or predicates
。
How may I implement the Value
trait for my ValueMap
struct when F
is a function that maps the value S
to something else?当F
是一个将值S
映射到其他东西的函数时,如何为我的ValueMap
结构实现Value
特征?
Remarks: I don't have this issue when I use associated types on Value.备注:当我在 Value 上使用关联类型时,我没有这个问题。 But the concepts are still a bit blurry for me.但是这些概念对我来说仍然有点模糊。
The details for error message #0E207 say that:错误消息#0E207的详细信息说:
Any type parameter or lifetime parameter of an
impl
must meet at least one of the following criteria:impl
任何类型参数或生命周期参数必须至少满足以下条件之一:
- it appears in the implementing type of the
impl
, egimpl<T> Foo<T>
它出现在impl
的实现类型中,例如impl<T> Foo<T>
- for a trait
impl
, it appears in the implemented trait, egimpl<T> SomeTrait<T> for Foo
对于 traitimpl
,它出现在已实现的 trait 中,例如impl<T> SomeTrait<T> for Foo
- it is bound as an associated type, eg
impl<T, U> SomeTrait for T where T: AnotherTrait<AssocType=U>
它绑定为关联类型,例如impl<T, U> SomeTrait for T where T: AnotherTrait<AssocType=U>
None of these hold for your T
.这些都不适合你的T
。 So what you're doing is currently not supported.因此,目前不支持您正在执行的操作。
It feels hacky, but I was able to get this to work by adding additional type parameters to ValueMap, backed by phantom data members.这感觉很糟糕,但我能够通过向 ValueMap 添加额外的类型参数来实现这一点,并由幻像数据成员支持。 This way each of the types does occur in the imlementing type, and the requirements are satisfied.这样每个类型确实出现在实现类型中,并且满足了要求。
trait Value<T> {
fn get(&self) -> T;
}
struct ValueMap<T, U, S, F>
where
F: Fn(T) -> U,
{
s: S,
f: F,
_t: std::marker::PhantomData<T>,
_u: std::marker::PhantomData<U>,
}
impl<T, U, S, F> Value<U> for ValueMap<T, U, S, F>
where
S: Value<T>,
F: Fn(T) -> U,
{
fn get(&self) -> U {
(self.f)(self.s.get())
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.