传递生命周期时,泛型类型参数不受约束
Generic type parameter is not constrained when passing lifetime
为什么下面的编译不通过?
trait A<'a> {
type Typ;
}
trait B {}
struct C<T> {
_ph: std::marker::PhantomData<T>,
}
impl<'a, T, V> B for C<T> where
T: A<'a, Typ=V>
{}
前面报错“类型参数V
不受impl trait、self type或predicates的约束”。将关联类型更改为泛型类型也不会编译,给出相同的错误。
但是,以下会在生命周期被移除后进行编译。
trait A {
type Typ;
}
trait B {}
struct C<T> {
_ph: std::marker::PhantomData<T>,
}
impl<T, V> B for C<T> where
T: A<Typ=V>
{}
删除关联类型也会编译。
trait A<'a> {}
trait B {}
struct C<T> {
_ph: std::marker::PhantomData<T>,
}
impl<'a, T> B for C<T> where
T: A<'a>
{}
看到仅删除生命周期如何导致代码编译(不以任何方式更改 V),我猜错误消息不是真正的潜在错误。我不知道不编译的真正原因是什么。
最初出现的情况并不相关 - 这个问题更多的是关于奇怪的行为和错误消息,但如果你愿意,你可以看看它here。
它抱怨是因为你没有限制那个泛型。
就像写:
impl<A> SomeTrait for MyType {}
// We aren't using A
这会很好用,因为它已经通用了 Typ
是什么:
impl<'a, T> B for C<T> where
T: A<'a>,
{
// you can refer to your V type as <T as A>::Typ
}
如果你确实想限制它,你可以:
use std::default::Default;
impl<'a, T> B for C<T> where
T: A<'a>,
<T as A<'a>>::Typ: Default,
{
// now here you can call <T as A<'a>>::Typ::default()
}
为什么下面的编译不通过?
trait A<'a> {
type Typ;
}
trait B {}
struct C<T> {
_ph: std::marker::PhantomData<T>,
}
impl<'a, T, V> B for C<T> where
T: A<'a, Typ=V>
{}
前面报错“类型参数V
不受impl trait、self type或predicates的约束”。将关联类型更改为泛型类型也不会编译,给出相同的错误。
但是,以下会在生命周期被移除后进行编译。
trait A {
type Typ;
}
trait B {}
struct C<T> {
_ph: std::marker::PhantomData<T>,
}
impl<T, V> B for C<T> where
T: A<Typ=V>
{}
删除关联类型也会编译。
trait A<'a> {}
trait B {}
struct C<T> {
_ph: std::marker::PhantomData<T>,
}
impl<'a, T> B for C<T> where
T: A<'a>
{}
看到仅删除生命周期如何导致代码编译(不以任何方式更改 V),我猜错误消息不是真正的潜在错误。我不知道不编译的真正原因是什么。
最初出现的情况并不相关 - 这个问题更多的是关于奇怪的行为和错误消息,但如果你愿意,你可以看看它here。
它抱怨是因为你没有限制那个泛型。
就像写:
impl<A> SomeTrait for MyType {}
// We aren't using A
这会很好用,因为它已经通用了 Typ
是什么:
impl<'a, T> B for C<T> where
T: A<'a>,
{
// you can refer to your V type as <T as A>::Typ
}
如果你确实想限制它,你可以:
use std::default::Default;
impl<'a, T> B for C<T> where
T: A<'a>,
<T as A<'a>>::Typ: Default,
{
// now here you can call <T as A<'a>>::Typ::default()
}